1. 프로퍼티
- 클래스 / 구조체 / 열거형과 연관된 값
- 타입과 관련된 값을 저장 / 연산가능
- 열거형 내부에는 연산 프로퍼티만 구현 가능
- 연산 프로퍼티는 var 로만 선언
- 연산 프로퍼티는 읽기전용으로는 구현 가능 / 쓰기 전용으로는 구현 할 수 없음
- 읽기전용으로 구현하려면 get 블럭만 작성하면 가능
- 읽기전용은 get블럭 생략 가능
- 읽기 / 쓰기 모두 가능하게 하려면 get / set 블럭을 보두 구현
- set 블럭에서 암시적 매개변수 newValue 사용가능
2. 프로퍼티 종류
- 인스턴스 저장
- 타입 저장
- 인스턴스 연산
- 타입 연산
- 지연 저장
3. 사용예
struct Student {
var name: String = ""
var `class`: String = "Swift"
var koreanAge: Int = 0
var westernAge: Int {
get{
return koreanAge - 1
}
set(inputValue) {
koreanAge = inputValue + 1
}
}
static var typeDescription: String = "학생"
func selfIntro () {
print("i am \(name)")
}
var readOnlySelfIntro: String {
get{
return "i am \(name)"
}
}
static func typeSelfIntro () {
print("student")
}
static var readOnlySelfInfro: String {
return "student type"
}
}
print(Student.readOnlySelfIntro)
var me: Student = Student()
me.koreanAge = 10
me.name = "me"
print(me.name)
print(me.readOnlySelfInrto)
4. 응용
struct Money {
var currencyRate: Double = 1100
var dollar: Double = 0
var won: Double {
get {
return dollar * currencyRate
}
set {
dollar = newValue / currencyRate
}
}
}
var moneyInMyPocket = Money()
moneyInMyPocket.won = 11000
print(moneyInMyPocket.won)
moneyInMyPocket.dollar = 10
print(moneyInMyPocket.won)
5. 프로퍼티 감시자
- 프로퍼티 감시자를 사용하면 값이 변결될 때 원하는 동작 수행가능
- 값 변경직전 willSet 블럭 호출
- 값 변경직후 didSet 블럭 호출
- 둘 중 하나만 구현해도 무관
- 변경값이 같더라도 항상 동작
- willSet : 암시적 매개변수 newValue 사용가능
- didSet : 암시적 매개변수 oldValue 사용가능
- 연산 프로퍼티에는 사용불가
struct Money {
var currencyRate: Double = 1100 {
willSet(newRate) {
print("rate to \(newRate)")
}
didSet(oldRate) {
print("rate from \(oldRate) to \(currencyRate)")
}
}
var dollar: Double = 0 {
willSet {
print("dollar to \(new)")
}
didSet {
print("dollar from \(oldDollar) to \(dollar)")
}
}
var won: Double {
get {
return dollar * currenctRate
}
set {
dollar = newValue / currencyRate
}
}
}
var money: Money = Money()
money.currencyRate = 1000
money.dollar = 10
print(money.won)