Structs and Classes
Struct Methods
Methods are functions attached to a type and called on an instance.
Call behavior on a value
struct_methods.swift
Replay: real traced execution (multi-file project)
struct Rectangle {
let width: Int
let height: Int
func area() -> Int {
return width * height
}
}
let width = 6
let rectangle = Rectangle(width: width, height: 4)
let area = rectangle.area()
print("width=\(width)")
print("area=\(area)")
struct Rectangle {
let width: Int
let height: Int
func area() -> Int {
return width * height
}
}
let width = 3
let rectangle = Rectangle(width: width, height: 4)
let area = rectangle.area()
print("width=\(width)")
print("area=\(area)")
struct Rectangle {
let width: Int
let height: Int
func area() -> Int {
return width * height
}
}
let width = 9
let rectangle = Rectangle(width: width, height: 4)
let area = rectangle.area()
print("width=\(width)")
print("area=\(area)")
width ← 6, rectangle ← Rectangle(width: 6, height: 4)
10let width→ 6 = 6 //@width=3, 911let rectangle→ Rectangle(width: 6, height: 4) = Rectangle(width: width6, height: 4)12let area = rectangleRectangle(width: 6, height: 4).area()func area() -> Int
5func area() -> Int {6 return width6 * height47}area ← 24
11let rectangle = Rectangle(width: width, height: 4)12let area→ 24 = rectangleRectangle(width: 6, height: 4).area()1314print("width=\(width6)")15print("area=\(area24)")outputwidth=6 area=24
width ← 3, rectangle ← Rectangle(width: 3, height: 4)
10let width→ 3 = 311let rectangle→ Rectangle(width: 3, height: 4) = Rectangle(width: width3, height: 4)12let area = rectangleRectangle(width: 3, height: 4).area()func area() -> Int
5func area() -> Int {6 return width3 * height47}area ← 12
11let rectangle = Rectangle(width: width, height: 4)12let area→ 12 = rectangleRectangle(width: 3, height: 4).area()1314print("width=\(width3)")15print("area=\(area12)")outputwidth=3 area=12
width ← 9, rectangle ← Rectangle(width: 9, height: 4)
10let width→ 9 = 911let rectangle→ Rectangle(width: 9, height: 4) = Rectangle(width: width9, height: 4)12let area = rectangleRectangle(width: 9, height: 4).area()func area() -> Int
5func area() -> Int {6 return width9 * height47}area ← 36
11let rectangle = Rectangle(width: width, height: 4)12let area→ 36 = rectangleRectangle(width: 9, height: 4).area()1314print("width=\(width9)")15print("area=\(area36)")outputwidth=9 area=36
Follow the Method
widthstarts as6.rectanglestores width6and height4.rectangle.area()calls the method on that rectangle.- The method returns
width * height. areabecomes24. | width | height | area | | --- | --- | --- | | 6 | 4 | 24 | | 3 | 4 | 12 | | 9 | 4 | 36 |
methods
A method can read the instance's properties and return a calculated result.
Exercise: struct_methods.swift
Reproduce width=6 and area=24, then use the pinned width variants 3 and 9 to predict area=12 and area=36.