Lesson 53Structs
Methods
What are Methods?
Methods are functions that belong to a struct. They can read properties, perform calculations, and modify the struct's state!
Method Types
Instance Methods
Called on struct instances
instance.method()Type Methods (static)
Called on the type itself
StructName.method()Mutating Methods
Methods that modify properties must be marked with mutating!
mutating func modify() { ... }
The self Keyword
self refers to the current instance - use it to distinguish property from parameter with same name!
main.swift
// STRUCT METHODS
// Methods are functions that belong to a struct
// INSTANCE METHODS
struct Counter {
var count: Int = 0
func displayCount() {
print("Current count: \(count)")
}
func isGreaterThan(_ value: Int) -> Bool {
return count > value
}
}
var counter = Counter()
counter.displayCount() // Current count: 0
// MUTATING METHODS
// Methods that modify struct properties must be marked 'mutating'
struct Player {
var name: String
var score: Int = 0
var level: Int = 1
mutating func addScore(_ points: Int) {
score += points
print("\(name) scored \(points) points! Total: \(score)")
}
mutating func levelUp() {
level += 1
print("\(name) leveled up to \(level)!")
}
func status() -> String {
return "\(name) - Level \(level), Score: \(score)"
}
}
var player = Player(name: "Alice")
player.addScore(100) // Alice scored 100 points!
player.levelUp() // Alice leveled up to 2!
// SELF KEYWORD
struct Point {
var x: Double
var y: Double
mutating func moveTo(x: Double, y: Double) {
self.x = x // self.x is property, x is parameter
self.y = y
}
func distanceTo(_ other: Point) -> Double {
let dx = self.x - other.x
let dy = self.y - other.y
return (dx * dx + dy * dy).squareRoot()
}
}
var p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
print(p1.distanceTo(p2)) // 5.0
// TYPE METHODS (Static)
struct MathHelper {
static func square(_ n: Int) -> Int {
return n * n
}
static func cube(_ n: Int) -> Int {
return n * n * n
}
}
print(MathHelper.square(5)) // 25
print(MathHelper.cube(3)) // 27Try It Yourself!
Create a BankAccount with deposit() and withdraw() mutating methods!