Lesson 3 / 25

Constants, Variables, Types and Strings

Use let and var, Swift's basic types, type safety and strings.

Values and types

Declare constants with let and variables with var; prefer let and switch to var only when a value must change, which the compiler suggests. Swift infers types from initial values, but types are fixed at compile time: let count = 3 is an Int forever. Basic types include Int (64-bit on modern platforms), Double, Float, Bool, String and Character. Swift never converts numbers implicitly: adding an Int to a Double requires Double(count), which prevents subtle precision bugs. Integer overflow traps at run time instead of silently wrapping (use &+ when wrapping is intended). Strings are Unicode-correct value types: count counts user-perceived characters (grapheme clusters), so emoji and Hindi text count sensibly, and indexing uses String.Index rather than integers because characters vary in size. Use string interpolation ("Total: \(total)") and multi-line literals with triple quotes. Tuples group values temporarily (let point = (x: 3, y: 4)), and typealias gives types readable names.

Types without implicit conversions

Explicit numeric conversion, Unicode-aware counting and tuples.

let quantity = 3                    // Int
let unitPrice = 49.5                // Double
let total = Double(quantity) * unitPrice   // explicit conversion required

let greeting = "नमस्ते 👋"
print(greeting.count)               // counts characters, not bytes
print(greeting.utf8.count)          // byte count is different

let firstWord = greeting.split(separator: " ").first ?? ""

let receipt = """
    Item:  Notebook
    Qty:   \(quantity)
    Total: \(total)
    """

typealias Coordinate = (latitude: Double, longitude: Double)
let pune: Coordinate = (18.52, 73.86)
print(pune.latitude)

let big = Int.max
// let overflow = big + 1            // traps at run time: arithmetic overflow
let wrapped = big &+ 1               // explicit wrapping arithmetic

Prefer let by default

Values declared with let cannot change, which makes code easier to reason about and lets the compiler optimise. Xcode warns when a var is never mutated.

Quick check: What happens when you add an Int and a Double directly in Swift?

  • The Int is converted automatically
  • The Double is truncated
  • It is a compile error; you must convert one explicitly
  • The result is a String
Answer

It is a compile error; you must convert one explicitly — Swift has no implicit numeric conversions, so you write Double(x) or Int(y).