Swift is a new programming language for iOS, as well as, OS X apps. As compared to Objective-C, Swift is a neat language and will definitely make developing iOS apps easier.
Variables, Constants and Type Inference:
In Swift, you declare variables with the “var” keyword and constants using the “let” keyword. Here is an example:
These are the two keywords you need to know for variable and constant declaration. You simply use the “let” keyword for storing value that is unchanged. Otherwise, use “var” keyword for storing values that can be changed.
Isn’t it easier than Objective-C?
What’s interesting is that Swift allows you to use nearly any character for both variable and constant names. You can even use an emoji character for the naming.
var numberOfRows = 30
let maxNumberOfRows = 100
let maxNumberOfRows = 100
Quick Tip
You may wonder how you can type an emoji character in Mac OS. It’s easy. Just press Control-Command-spacebar and an emoji picker will be displayed.
You may notice a huge difference in variable declaration between Objective-C and Swift. In Objective-C, developers have to specify explicitly the type information when declaring a variable. Be it an int or double or NSString, etc.
It’s your responsibility to specify the type. For Swift, you no longer need to annotate variables with type information. It provides a huge feature known as Type inference. This feature enables the compiler to deduce the type automatically by examining the values you provide in the variable.
It makes variable and constant declaration much simpler, as compared to Objective-C. Swift provides an option to explicitly specify the type information if you wish. The below example shows how to specify type information when declaring a variable in Swift:
var myMessage : String = "Swift is the future!
No Semicolons:
In Objective-C, you need to end each statement in your code with a semicolon. If you forget to do so, you will end up with a compilation error.
As you can see from the above examples, Swift doesn’t require you to write a semicolon (;) after each statement, though you can still do so if you like.
var myMessage = "No semicolon is needed"const int count = 10;
double price = 23.55;
NSString *myMessage = @"Objective-C is not dead yet!";
// count is inferred to be of type Int
var price = 23.55
// price is inferred to be of type Double
var myMessage = "Swift is the future!"
// myMessage is inferred to be of type String
let count = 10