참조(Reference) 타입: 클래스, 함수(객체), 클로저
나머지 모두 값(Value) 타입
구조체는 값 타입이기 때문에 구조체 메소드 내에서 프로퍼티를 수정할 수 없음
메소드 내에서 프로퍼티 수정하려면 mutating 키워드 사용
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
withUnsafePointer(to: &somePoint) { (p) in
print(p) //0x00007ffeeb538570
}
somePoint.moveBy(x: 2.0, y: 3.0)
withUnsafePointer(to: &somePoint) { (p) in
print(p) //0x00007ffeeb538570
}
//혹시나 해서 주소값을 찍어 봤는데 주소값이 바뀌진 않는군요!
값 타입의 변수를 함수 파라미터로 넘길 때 참조로 넘길 수 있는 키워드, inout
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
//엄청난 크기의 Array(값타입)를 함수 파라미터로 넘길 때 참조로 넘겨서 복사를 방지함
func calcSomething(_ array: inout [Int]) {
array.remove(at: 10)
}
var array = [Int]()
for i in 0 ..< 10000000 {
array.append(i)
}
calcSomething(&array)
The Swift Programming Language (Swift 5.1) 참조했습니다.