Appendix B. Swift syntax cheat sheets

Variables and constants

var aVariable = 0
let aConstant = 0

Data type annotations

var aString: String
var aBool: Bool
var aInt: Int
var aDouble: Double

Data type inference

var bString = "A String!"
var bBool = true
var bInt = 3
var bDouble = 3.0

Clarify data type

var cDouble: Double = 3

Convert data type

var dDouble = Double(3)

Property observers

var score = 0 {
  willSet {
    // Score will be updated
  }
  didSet {
    // Score was updated
  }
}

String interpolation

var message = "You scored\(score)"

Collections

Arrays

var emptyArray: [String] = []
var arrayOfInts = [3, 1, 2, 5]
arrayOfInts.append(4)

Dictionaries

var emptyDictionary: [String: String] = [:]
var dict = ["A": 1, "B": 2, "C": 3]
dict["D"] = 4

Get iOS Development with Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.