Exploring Swift: Variables and Constants

6 minute read

In this series of post I'll try to cover Swift in detailed manner to help myself, and hopefully you too, learn Swift in detail. Swift does has good language guide published by Apple which is available on iBooks Store, but given the nature of being such expressive language, there are tons of things which are not apparent from the first glance and really obscure in when things get complicated.

I will not focus on Cocoa and Cocoa Touch in few upcoming posts. This is not "Getting Started with iOS Development" kind of posts. I will focus on language itself. I'll try cover interoperability of existing frameworks, Objective-C code and the Swift later.

So, without further ado, let's get started:

Variables and constants

Variables and constants seem to be very straight forward in Swift. Both have to declared before use using var and let keywords respectively. Constants cannot be changed in future execution of program and must me initialized with its value immediately.

let numberOfMaximumCarsInParking = 1000 // set or get compile error

Variables can change during program and could be declared without initialization, albeit using them in expressions will throw compile error. Uninitialized variables must have type annotation. This is only case (I couldn't find another yet) where type annotation is required throwout the language. If you provide initial value to variable, there is no need to annotation it.

var numberOfFreeSpacesInParking = 123

var carParkingName:String; // this is fine, but type has to be annotated

carParkingName = "Underground on Some Street"

// Comment line above and you'll get compile error in if statement
// because you can not use uninitialised variable
if carParkingName == "Underground on Some Street" {
    "You are here"

For compactness you can declare multiple variables and multiple constants in a single line, separated by comas.

var x = 1, y = 2, z = "This is string" // Works for constants too

Redeclaring of variable and constants with same name is prohibited, even if you change store value.

Swift seems to be proud to allow you using any Unicode characters as a variable name. So proud in fact that guide even shows how to use Emoji as an example of variable name. Please don't do this, or you'll end up with something that looks like this.

let 🍆 = "fisteggplant"

Value Types

There are two types of containing values in Swift: value types and reference types. A value type is a type that is copied when it is assigned to a variable or constant, or when it is passed to a function. Structures and enumerations (enums) are value types. As you might already guessed, classes are reference types.

Here is an example of how different value types behave when passed to array: (Same will apply to any expression.)

// For Value Types
let numbers = [x,y]         // [1,2] as constant
x = 5
numbers                     // again [1,2] and no error
numbers[0] = 5              // this will work
numbers                     // [5,2]

// For reference types
class MyNumber {
    init (value:Int = 0){
        self.valueNumber = value
    var valueNumber:Int;
    var value:Int {
        get {
            return valueNumber
        set {
            valueNumber = newValue

let a = MyNumber(value:4)
var b = MyNumber(value:7)

let myNumbres = [a,b]       // [4,7] as constant
a.value = 7                 // a is instance, thus reference type
myNumbres                   // [7,7] 

What about primitives like Int or Bool? In Swift, there are no primitives! That's whole beauty and point of Swift. What looks like a primitive for you, is actually a stuct, thus are value types.

Note that String is also struct, and passed by value.


There are no mutable and immutable breeds of same class in Swift as in Objective-C. You specify mutability by declaration. Everything declared with var is considered mutable and by let—immutable.

But, if you paid close attention to example code above, you might notice odd behaviour from Array which was declared as constant (read: immutable), but was clearly mutable.

let numbers = [x,y]         // [1,2] as constant
numbers[0] = 5              // this works fine, but why?

let is overloaded to dictate immutability for value types, not reference types. So changing mutable instance property of class which is referenced by immutable array seems obvious now. Problem is that, array in Swift is declared as a structure.

From my observation, reference you hold on Swift array, is reference to the buffer in memory and by using let you make that reference immutable. Because arrays in Swift buffer look fairly simple [length,capacity,item1,item2,...] you can exchange items with same type/capacity but cannot change length, thus making it impossible to append, pop and so on. Declaring array as a variable will "unlock" those functionalities.

Apple strongly recommends to use constants in cases where variables appear to not change its lifecycle.

I'll cover more on arrays and dictionary in future posts.

Printing Values

println(value:String) is new NSLog(). It will print out in console, both when working with Playgrounds (located in Assistant Editor) or in Xcode project.

Swift support String interpolation, thus println() can use it as its advantage and printout any constant, variable or another long string as a part of its string like so:

println("Currently \(carParkingName) has \(numberOfFreeSpacesInParking) free parking places")


Few word on comments. They are as you'd expect them too be with one neat addition. In swift you can nest /* ... */ multiline comments. Yay!

/* This is multiline comment

    /* So this is, but interesting part is one line below */

    This line, would be illegal in some languages,
    but in Swift also belongs to comment scope above.

let isSwiftMultilineCommentAwesome = true

That's it for now. I will update this post if I find more details on obscure behaviours or find more relevant information about constants and variables.

You can download playground with sample code above from GitHub.

If you enjoy reading you should follow @totocaster on Twitter. In case you have something to add and/or provide feedback—feel free to do so by writing to toto@totocaster.com. For more articles and linked resources subscribe to myRSS feed.