Swift
Beginner
1 min read
Classes and Structs
Example
// Struct - value type
struct Point {
var x: Double
var y: Double
// Memberwise initializer provided automatically
func distanceTo(_ other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return (dx*dx + dy*dy).squareRoot()
}
// mutating required to modify stored properties
mutating func move(by delta: Point) {
x += delta.x
y += delta.y
}
}
var p1 = Point(x: 0, y: 0)
var p2 = p1 // independent copy
p2.x = 5
print(p1.x, p2.x) // 0.0 5.0
// Class - reference type
class Counter {
var count = 0
func increment() { count += 1 }
func reset() { count = 0 }
}
let c1 = Counter()
let c2 = c1 // same object
c2.increment()
print(c1.count) // 1 (shared reference)
// Computed properties
struct Rectangle {
var width: Double
var height: Double
var area: Double { width * height }
var perimeter: Double { 2 * (width + height) }
}