Swift Language Fundamentals: Types, Constants, and Inference
Types, constants, and inference
Swift is statically typed and type-safe: every variable has a definite type at compile time, and the compiler infers it from the initializer. Use let for values that never change and var only when mutation is required. A let may be assigned once later, provided the compiler can prove it is initialized before every use.
Core types include Int, Double, Bool, String, tuples, arrays, dictionaries, and sets. Swift does not perform implicit numeric conversions: adding an Int to a Double requires Double(count). Integer division truncates toward zero, so 7 / 2 is 3; mix in a Double literal to get 3.5. Numeric literals accept underscores and exponents (1_000_000, 1e3).
Strings are collections of Character values, not integer-indexed arrays. Use startIndex, index(_:offsetBy:), and count; subscripts take String.Index. Interpolation uses \(expression) and converts values automatically.
Traps candidates miss
- Assuming
varis needed for reference types;letstill permits mutating a class instance's properties. - Expecting implicit
Int/Doublebridging. - Treating
String.countas a cheap constant-time operation; it is not. - Forgetting that tuple labels are part of the type but tuple values are copied.
Rule of thumb
Default to let and immutability. When a numeric expression surprises you, annotate the intended type explicitly: let average: Double = Double(total) / Double(count).