<aside> 💡 저장 프로퍼티(stored properties) 연산 프로퍼티(computed properties) 타입 프로퍼티(type properties)
</aside>
<aside> 📜 저장 프로퍼티는 read-only, 값 변경 불가능
변경하고 싶으면 setter
을 추가하기. ( → 연산 프로퍼티 )
타입 프로퍼티 : 생성된 인스턴스와 상관없이 타입 자체의 속성을 정하고 싶을 때 ( static
)
</aside>
class Pokemon {
let name: String = "Pikachu"
var age: Int = 1
}
struct Digimon {
let name: String = "아구몬"
var age: Int = 1
}
-> 이 경우에는 name 상수와 age 변수 모두 저장 프로퍼티
let pokemonList : Pokemon? = Pokemon()
pokemonList?.name = "메타몽" // Cannot assign to property: 'name' is a 'let' constant
pokemonList?.age = 12
let digimonList : Digimon? = .init()
digimonList?.name = "아구몬" // Cannot assign to property ( ... )
digimonList?.age = 12 // Cannot assign to property ( ... )
클래스의 경우
구조체의 경우
예시 )
//좌표
struct CoordinatePoint {
var x: Int = 0 //저장 프로퍼티
var y: Int = 0 //저장 프로퍼티
}
//프로퍼티에 초깃값을 할당했다면 굳이 전달인자로 초깃값을 넘길 필요가 없습니다
let yagomPoint: CoordinatePoint = CoordinatePoint()
//물론 기존에 초깃값을 할당할 수 있는 이니셜라이저도 사용 가능합니다.
let wizplanPoint: CoordinatePoint = CoordinatePoint(x: 10, y: 5)
print("yagom's point : \\(yagomPoint.x), \\(yagomPoint.y)") //yagom's point : 0, 0
print("wizplan's point : \\(wizplanPoint.x), \\(wizplanPoint.y)") //wizplan's point : 10,5
//사람의 위치 정보
class Position {
var point: CoordinatePoint = CoordinatePoint //저장 프로퍼티
let name: String = "Unknown" //저장 프로퍼티
//초깃값을 지정해줬다면 사용자 정의 이니셜라이저를 사용하지 않아도 됩니다.
let yagomPosition: Position = Position()
yagomPosition.point = yagomPoint
yagomPosition.name = "yagom"