Introduction to Swift : Variables and Constants

This year at WWDC Apple released a brand new language called Swift. This will change the way iOS will be developed in the near future and older Objective-C code is expected to migrate gradually. In this serie of tutorials we will go over the main aspects of the Swift language.

To develop in Swift you will need Xcode 6, which can be downloaded at Apple's developer portal. Xcode has an option to experiment with  the Swift language called Playgrounds. Launch Xcode 6, go to File\New\File. Select iOS\Source\Playground, and click Next. Give your playground a name and save it to disk. To view the output of the code, press the round circle on the right side to open the Assistant Editor.

Basic Types

The basic types in the Swift language are:

  • Int : 5, 100
  • Float or Double: 0.5, 3.7899
  • Bool: true or false
  • String: "Hello Swift"

Note in Objective-C the boolean values are YES or NO, in swift this has changed to true or false.

Declaring Variables

Swift is a strong typed language, which means the compiler knows the type of an object. This reduces much programming errors and is also faster to compile. To declare variables in Swift you can use the following general syntax.

var name:type = value

The variables can be explicitly declared. Some examples are

var myNumber:Int = 5
var myString:String = "Hello Swift"

Variables in Swift can also be inferred, which means the compiler can figure out the type of a variable based on the assigned value.

var myNumber = 5
var myString = "Hello Swift"

Variables and Constants

Until now we have used the var keyword to declare variables. This means the value can be changed after declaration. Swift also uses constants with the let keyword, the value can't be changed.

var myNumber = 5
let myString = "Hello Swift"

myNumber = 6
myString = "Just Learning" // compiler error


Swift supports the full Unicode character set. This means your variables can be named using special characters.

let π = 3.1415926 

The π character can be entered with the Option + p keys. This finished this part of the introduction serie of Swift programming. Expect lots of Swift tutorials in the near future.