App Development with Swift study materials
App Development with Swift study resources

App Development with Swift: Swift Language Fundamentals: Types, Constants, and Inference

App Development with Swift · Work through your exam, one topic at a time.

All guide sections

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 var is needed for reference types; let still permits mutating a class instance's properties.
  • Expecting implicit Int/Double bridging.
  • Treating String.count as 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).