SwSwift
BeginnerLesson 2 of 16

Variables, Constants & Types – Swift

let and var, type inference, and the most important basic types.

With let you create a constant, with var a variable. Swift recommends: use let by default, and only switch to var when the value really has to change. The type is inferred from the value (type inference).

let name = "Ada"           // String
var alter = 36              // Int
alter += 1
let groesse: Double = 1.68  // type given explicitly
let aktiv = true            // Bool
let buchstabe: Character = "🙂"

print(type(of: alter), type(of: groesse))   // Int Double

Swift never converts types implicitly. You convert between Int and Double explicitly using the initializer of the target type. Converting text to a number returns an optional, because it can go wrong:

let a = 7, b = 2
print(a / b)                         // 3   (Int division)
print(Double(a) / Double(b))         // 3.5
print(a % b)                         // 1
print(Int("42") ?? 0, Int("abc") ?? 0)   // 42 0
print(Int(3.99), Double(5))          // 3 5.0

let punkt = (x: 4, y: 7)             // tuple with names
print(punkt.x, punkt.1)              // 4 7
let (px, py) = punkt                 // destructuring
print(px + py)                       // 11

Important types: Int (64 bits on modern systems), Double (the default for floating-point numbers), Float, Bool, String, Character, as well as UInt, Int8 … Int64. Large numbers can be made readable with underscores: 1_000_000.

let million = 1_000_000
let hex = 0xFF                 // 255
let binaer = 0b1010            // 10
print(million, hex, binaer, Int.max)

let ueberlauf = Int.max &+ 1   // &+ : overflow allowed (wrap-around)
print(ueberlauf == Int.min)    // true
WarningA regular overflow (Int.max + 1) aborts the program (trap); Swift never stays silent here. If you need wrap-around, use &+, &-, &*, or addingReportingOverflow.
TipWith Option-click on a name in Xcode you can see the inferred type. Explicit type annotations help with readability and with literals (let x: Double = 5).