let VS var
struct
- 구조체의 경우, 그 안의 프로퍼티 값을 변경하려면 무조건 var로 인스턴스를 생성해야된다.
- 단, 프로퍼티는 Struct 안에서 var로 선언되어있어야된다.
struct Struct {
var string = "happy"
}
let structInstance = Struct()
structInstance.string = "sad" // error
class
- 클래스의 경우, 그 안의 프로퍼티 값을 변경할 때, var나 let이나 상관없이 인스턴스를 생성해주면된다.
- 단, 프로퍼티는 클래스 안에서 var로 선언되어있어야된다.
class Class {
var string = "happy"
}
let classInstance = Class()
classInstance.string = "sad" // OK
즉, 구조체의 경우 그 안에 있는 프로퍼티 값이 변경될 경우, 구조체를 무조건 var로 선언을 해야된다!
즉, 클래스일 경우 그 안에 있는 프로퍼티 값이 변경될 경우, let이나 var나 상관없다!
구조체 안에 클래스가 있는 경우
- 구조체 안에 있는 클래스 타입의 프로퍼티의 프로퍼티를 변경할 경우!
- 복사본이 변경되면 원본도 변경이된다!(클래스의 프로퍼티)
class Class {
var string = "happy"
}
struct Struct {
var string = "happy"
// let이던 var던 상관없다!
let classType = Class()
}
let structInstance = Struct()
// 무조건 var여야된다!
var copiedStructInstance = structInstance
copiedStructInstance.string = "sad"
copiedStructInstance.classType.string = "sad"
structInstance.string // "happy" -> 복사값이 변경되어도 원본값은 변경되지 않는다.
structInstance.classType.string // "sad" -> 원본값도 변경이된다.
클래스 안에 구조체가 있는 경우
- 클래스 안에 있는 구조체 타입의 프로퍼티의 프로퍼티 값을 변경할 경우
- 복사본이 변경되면 원본값도 변경된다!
struct Struct {
var string = "happy"
}
class Class {
var string = "happy"
// let으로 설정하면 error 생긴다.
var structType = Struct()
}
let classInstance = Class()
let copiedClassInstance = classInstance
copiedClassInstance.string = "sad"
copiedClassInstance.structType.string = "sad"
classInstance.string // "sad"
classInstance.structType.string // "sad"
'Swift' 카테고리의 다른 글
[Swift] Enumeration(열거형) (0) | 2023.03.06 |
---|---|
[Swift] mutating (0) | 2023.02.24 |
[Swift] 함수 return에대한 고민 (0) | 2023.02.20 |
[Swift] Error Handling (0) | 2023.02.11 |
[Swift] 프로퍼티 옵저버 (0) | 2023.02.11 |