Constants, Variables and Basic Types

3.1 let and var

Use let by default. Use var only when the value must change. The compiler warns about vars that are never mutated.

let maxUsers = 100              // constant (immutable): prefer let
var currentUsers = 0            // variable (mutable)
currentUsers += 1

let pi: Double = 3.14159        // explicit type annotation
var message: String             // declare now, assign later (must be assigned before use)
message = "Hello"

let a = 1, b = 2, c = 3
var x = 0.0, y = 0.0

3.2 Basic Types

Platform-width signed integer (64-bit on modern platforms) Int8, Int16, Int32, Int64, Int128 (6.0) Sized signed integers UInt, UInt8... UInt128

64-bit floating point (the default for decimals) Float, Float16 32/16-bit floating point true / false A single extended grapheme cluster Decimal (Foundation) Base-10 decimal (money) Decimal(string: "9.99")

3.3 Literals and Type Inference

let decimal = 17
let binary = 0b10001
let octal = 0o21
let hex = 0x11
let million = 1_000_000
let scientific = 1.25e2         // 125.0
let hexFloat = 0xFp2            // 60.0
let inferredDouble = 3 + 0.14   // Double

3.4 Type Conversion (Always Explicit)

let count = 3
let ratio = 0.5
let total = Double(count) * ratio       // must convert explicitly
let truncated = Int(9.99)               // 9
let rounded = Int((9.5).rounded())      // 10
let parsed = Int("42")                  // Int? (Optional): may fail
let text = String(42)
let safeNarrow = Int8(exactly: 300)     // nil (doesn't fit)
let clamped = Int8(clamping: 300)       // 127
let bits = Int8(truncatingIfNeeded: 300) // 44

3.5 Type Aliases and Numeric Limits

typealias Seconds = Double
let timeout: Seconds = 30
print(Int.max, Int.min, UInt8.max, Double.infinity, Double.nan.isNaN, Double.ulpOfOne)

3.6 Tuples (Quick Introduction)

let httpError = (404, "Not Found")
let (code, message) = httpError
let named = (statusCode: 200, description: "OK")
print(named.statusCode, httpError.0)