iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Basic Types

Swift has three structural categories: value types (struct, enum, tuple), reference types (class, actor), and protocols (interfaces). Value types are the default — safer, faster, simpler.

Value vs reference in practice

EXAMPLE
// Struct (value type) — copied on assignment
struct Point {
    var x: Double
    var y: Double
    mutating func shift(by d: Double) { x += d; y += d }
}

var p1 = Point(x: 1, y: 2)
var p2 = p1            // independent copy
p2.shift(by: 10)
print(p1, p2)          // p1 unchanged, p2 moved

// Class (reference type) — shared identity
class Counter {
    var n = 0
    func bump() { n += 1 }
}

let a = Counter()
let b = a              // SAME instance
b.bump()
print(a.n)             // 1 — both see it

// Enum — algebraic data type
enum Result<T> {
    case success(T)
    case failure(Error)
}

// Protocol — interface, conformed to by any type
protocol Greet {
    func hello() -> String
}

struct User: Greet {
    let name: String
    func hello() -> String { "Hi, \(name)" }
}

Why it matters

Reach for struct by default. Use class only when you NEED reference semantics (identity, shared mutable state, ObjC interop). Modern SwiftUI code is 90% structs.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
let n: Int = 7
let f: Double = 3.14
let s: String = "hi"
let b: Bool = true
Try it Yourself »

Discussion

Loading…