외부에서 읽기만 가능하고 내부에서만 수정이 가능하도록 하는 키워드에요.
아래의 코드를 봅시다.
struct Mypet {
var title: String = "No title"
private(set) var name: String = "이름 없음"
mutating func setName(to newName: String) {
self.name = name
}
}
var myPet = MyPet()
위에 코드에서 보다시피 private(set) var name으로 이름을 지정해 주었어요.
이 코드는 밖에서는 읽는 것은 가능 하지만 직접 셋팅하는 것은 안돼요.
print(myPet.name) // "이름 없음"
myPet.name = "야옹이" // Error!! : Cannot assign to property: 'name' setter is inaccessible
하지만 name은 mutating으로 선언된 함수가 있어서 그것으로 바꿀 수 있습니다.
myPet.setName(to: "아쿠")
print(myPet.name) // "아쿠"