Structs and Classes
Compare value-type structs with reference-type classes and inheritance.
Code
import Foundation
// Struct: value type
struct PointStruct {
var x: Double
var y: Double
mutating func moveBy(dx: Double, dy: Double) {
x += dx; y += dy
}
}
// Class: reference type, supports inheritance and deinit
class Animal {
let name: String
init(name: String) { self.name = name }
func speak() -> String { "\(name) makes a sound" }
deinit { print("\(name) deinit") }
}
class Dog: Animal {
override func speak() -> String { "\(name) says woof" }
}
// Value semantics: copy on assignment
var p1 = PointStruct(x: 1, y: 2)
var p2 = p1
p2.moveBy(dx: 10, dy: 10)
print(p1, p2) // p1 unchanged
// Reference semantics: shared instance
let a = Dog(name: "Rex")
let b = a
print(a.speak(), b.speak())
// Equatable conformance
struct Money: Equatable {
let amount: Double
let currency: String
static func == (l: Money, r: Money) -> Bool {
l.amount == r.amount && l.currency == r.currency
}
}
print(Money(amount: 5, currency: "USD") == Money(amount: 5, currency: "USD"))Explanation
Structs are value types copied on assignment, making them safe for small immutable data. Classes are reference types that support inheritance, identity, and deinit for resource cleanup. Choose structs by default and reach for classes only when you need shared mutable state or subclassing.
More Swift Snippets
Optionals
Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.
Closures
Define closure expressions, capture state, and pass escaping callbacks.
Protocols
Define contracts, conform with structs, and add default behavior via extensions.
Generics
Write type-parameterized functions and types with protocol constraints.
Error Handling
Throw and catch typed errors with do-catch, try?, try!, and rethrows.
Concurrency (async/await)
Run async functions, parallelize with async let, and fan out with task groups.