상속시 재정의가 가능하다. → class 키워드를 사용해야한다.
class Shape {
static var length: Double = 0, width: Double = 0
class var area: Double{
return length * width
}
}
class Circle: Shape{
static override var area: Double{
return length * length * 3.14
}
}
계산 속성 → 메서드이기 때문에 메모리 공간 할당 x
class Circle {
static var multiPi: Double{
return pi * 2
}
}
class Profile1 {
var statusMessage: String {
willSet(message) { // 바뀔 값이 파라미터로 전달
print("메세지가 \(statusMessage)에서 \(message)로 변경될 예정입니다.")
print("상태메세지 업데이트 준비")
}
didSet(message) { // 바뀌기 전의 과거값이 파라미터로 전달
print("메세지가 \(message)에서 \(statusMessage)로 이미 변경되었습니다.")
print("상태메세지 업데이트 완료")
}
}
init(message: String) {
self.statusMessage = message
}
}
let profile1 = Profile1(message: "기본 상태메세지")
profile1.statusMessage = "기분 좋아졌으"
메세지가 기본 상태메세지에서 기분 좋아졌으로 변경될 예정입니다.
상태메세지 업데이트 준비
메세지가 기본 상태메세지에서 기분 좋아졌으로 이미 변경되었습니다.
상태메세지 업데이트 완료let profile1 = Profile1(message: "기본 상태메세지")
profile1.statusMessage = "기본 상태메세지"
파라미터로 넘겨주는게 부담스러울 수도 있다.
willSet이 실행될때는 기존 값이 변경되기 전인 상태이다 → 변경될 값을 - newValue 이용
didSet이 실행될대는 새로운 값으로 변경된 상태이다 → 기존값을 oldValue 이용
class Profile2 {
var statusMessage = "기본 상태메세지" {
willSet {
print("메세지가 \(statusMessage)에서 \(newValue)로 변경될 예정입니다.")
print("상태메세지 업데이트 준비")
}
didSet {
print("메세지가 \(oldValue)에서 \(statusMessage)로 이미 변경되었습니다.")
print("상태메세지 업데이트 완료")
}
}
}