Swift11 - νλ‘νΌν°
Properties
Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.
νλ‘νΌν°λ
- μ μ₯ νλ‘νΌν°λ ꡬ쑰체, ν΄λμ€ λ΄λΆμμ μμ λλ λ³μμ κ°μ μ μ₯
- μ°μ° νλ‘νΌν°λ ꡬ쑰체, ν΄λμ€, μ΄κ±°ν λ΄λΆμμ κ°μ κ³μ°
- μ°μ° νλ‘νΌν°λ varλ‘λ§ μ μΈν μ μμ΅λλ€.
- μ°μ°νλ‘νΌν°λ₯Ό μ½κΈ°μ μ©μΌλ‘λ ꡬνν μ μμ§λ§, μ°κΈ° μ μ©μΌλ‘λ ꡬνν μ μμ΅λλ€.
- μ½κΈ°μ μ©μΌλ‘ ꡬννλ €λ©΄ get λΈλλ§ μμ±ν΄μ£Όλ©΄ λ©λλ€. μ½κΈ°μ μ©μ getλΈλμ μλ΅ν μ μμ΅λλ€.
- μ½κΈ°, μ°κΈ° λͺ¨λ κ°λ₯νκ² νλ €λ©΄ get λΈλκ³Ό setλΈλμ λͺ¨λ ꡬνν΄μ£Όλ©΄ λ©λλ€.
- set λΈλμμ μμμ λ§€κ°λ³μ newValueλ₯Ό μ¬μ©ν μ μμ΅λλ€.
νλ‘νΌν°μ’ λ₯
- Stored property / Computed property
- instance property / type property
- Lazy Stored Properties : A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
νλ‘νΌν° ꡬν
struct Student {
// μΈμ€ν΄μ€ μ μ₯ νλ‘νΌν°
var name: String = ""
var koreanAge: Int = 0
// μΈμ€ν΄μ€ μ°μ° νλ‘νΌν°
var westernAge: Int {
get {
return koreanAge - 1
}
set(inputValue) {
koreanAge = inputValue + 1
}
}
// νμ
μ μ₯ νλ‘νΌν°
static var typeDescription: String = "νμ"
// μ½κΈ°μ μ© νμ
μ°μ° νλ‘νΌν°
// μ½κΈ°μ μ©μμλ getμ μλ΅ν μ μμ΅λλ€
static var selfIntroduction: String {
return "νμνμ
μ
λλ€"
}
}
var s1 = Student()
s1.name = "kim"
s1.koreanAge = 10
print(s1.westernAge) // 9
Property Observers
Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
You can add property observers in the following places:
- Stored properties that you define
- Stored properties that you inherit
- Computed properties that you inherit
νλ‘νΌν°κ°μμλ?
νλ‘νΌν° κ°μμλ₯Ό μ¬μ©νλ©΄ νλ‘νΌν°μ κ°μ΄ λ³κ²½λ λ μνλ λμμ μνν μ μμ΅λλ€.
κ°μ΄ λ³κ²½λκΈ° μ§μ μ willSetλΈλμ΄, κ°μ΄ λ³κ²½λ μ§νμ didSetλΈλμ΄ νΈμΆλ©λλ€.
λ μ€ νμν νλλ§ κ΅¬νν΄ μ£Όμ΄λ 무κ΄ν©λλ€.
λ³κ²½λλ €λ κ°μ΄ κΈ°μ‘΄ κ°κ³Ό λκ°λλΌλ νλ‘νΌν° κ°μμλ νμ λμν©λλ€.
willSet λΈλμμλ μμμ λ§€κ°λ³μ newValueλ₯Ό, didSet λΈλμμλ oldValueλ₯Ό μ¬μ©ν μ μμ΅λλ€.
νλ‘νΌν° κ°μμλ μ°μ° νλ‘νΌν°μλ μ¬μ©ν μ μμ΅λλ€.
νλ‘νΌν° κ°μμλ ν¨μ, λ©μλ, ν΄λ‘μ , νμ λ±μ μ§μ/μ μ λ³μμ λͺ¨λ μ¬μ© κ°λ₯ν©λλ€.
νλ‘νΌν°κ°μμ ꡬν
struct Money {
var currencyRate: Double = 1100 { // νλ‘νΌν° κ°μμ μ¬μ©
willSet(newRate) {
print("νμ¨μ΄ \(currencyRate)μμ \(newRate)μΌλ‘ λ³κ²½λ μμ μ
λλ€")
}
didSet(oldRate) {
print("νμ¨μ΄ \(oldRate)μμ \(currencyRate)μΌλ‘ λ³κ²½λμμ΅λλ€")
}
}
}
var moneyInMyPocket: Money = Money()
// νμ¨μ΄ 1100.0μμ 1150.0μΌλ‘ λ³κ²½λ μμ μ
λλ€
moneyInMyPocket.currencyRate = 1150
// νμ¨μ΄ 1100.0μμ 1150.0μΌλ‘ λ³κ²½λμμ΅λλ€