Tutorial by Examples

Declare a new variable with var, followed by a name, type, and value: var num: Int = 10 Variables can have their values changed: num = 20 // num now equals 20 Unless they're defined with let: let num: Int = 10 // num cannot change Swift infers the type of variable, so you don't always ha...
Properties can be added to a class or struct (technically enums too, see "Computed Properties" example). These add values that associate with instances of classes/structs: class Dog { var name = "" } In the above case, instances of Dog have a property named name of type...
Lazy stored properties have values that are not calculated until first accessed. This is useful for memory saving when the variable's calculation is computationally expensive. You declare a lazy property with lazy: lazy var veryExpensiveVariable = expensiveMethod() Often it is assigned to a retu...
Different from stored properties, computed properties are built with a getter and a setter, performing necessary code when accessed and set. Computed properties must define a type: var pi = 3.14 class Circle { var radius = 0.0 var circumference: Double { get { ret...
Local variables are defined within a function, method, or closure: func printSomething() { let localString = "I'm local!" print(localString) } func printSomethingAgain() { print(localString) // error } Global variables are defined outside of a function, method, or c...
Type properties are properties on the type itself, not on the instance. They can be both stored or computed properties. You declare a type property with static: struct Dog { static var noise = "Bark!" } print(Dog.noise) // Prints "Bark!" In a class, you can use the c...
Property observers respond to changes to a property's value. var myProperty = 5 { willSet { print("Will set to \(newValue). It was previously \(myProperty)") } didSet { print("Did set to \(myProperty). It was previously \(oldValue)") } } m...

Page 1 of 1