: νλ‘νΌν°λ₯Ό κ΄μ°°(observe)νλ©΄μ λ³κ²½ μ¬νμ΄ λ°μν λ μ€ν
willSet보λ€λ didSetμ΄ λ§μ΄ μ¬μ©λ¨
didSet
μ μ κ°μ΄ μ μ₯λ μ§νμ νΈμΆ
μ΄μ νλ‘νΌν°μ κ°μ΄
oldValue
λ‘ μ 곡
willSet
μ κ°μ΄ μ μ₯λκΈ° μ§μ μ νΈμΆ
μλ‘μ΄ νλ‘νΌν°μ κ°μ΄
newValue
λ‘ μ 곡
var name: String = "Unknown" {
willSet {
print("νμ¬ μ΄λ¦ = \(name), λ°λ μ΄λ¦ = \(newValue)")
} // newValμ λ³κ²½ λ μλ‘μ΄ κ°
didSet {
print("νμ¬ μ΄λ¦ = \(name), λ°λκΈ° μ μ΄λ¦ = \(oldValue)")
} // oldValμ λ³κ²½ μ myPropertyμ κ°
}
name = "Peter"
// willSetμ΄ λ¨Όμ μ€νλ¨
// νμ¬ μ΄λ¦ = Unknown, λ°λ μ΄λ¦ = Peter
// νμ¬ μ΄λ¦ = Peter, λ°λκΈ° μ μ΄λ¦ = Unknown
νλ‘νΌν° μ΅μ λ²λ₯Ό νμ©νλ©΄ κΈ°μ‘΄ νλ‘νΌν° κ°μ μμ λ λλ§λ€, λμμ κ°μ΄ λ³κ²½λ κ²μ μΈμ§νκ³ μ§μ λ λμμ μ€ν
: λ³μλ κ°μ²΄μ νμ μ λ€λ₯Έ νμ μΌλ‘ λ³ννλ νλ‘μΈμ€
νμ μ΄λ?
- κΈ°λ³Έ λ°μ΄ν° νμ (Int, Double, Bool, String) λ±
- μ΅μ λ(Optional)
- 컀μ€ν λ°μ΄ν° νμ (struct, class, enum, protocol λ±)
// Personμ μνΌ ν΄λμ€(λΆλͺ¨ ν΄λμ€)
class Person {
}
// Studentλ μλΈ ν΄λμ€(μμ ν΄λμ€) - μμλ°μ ν΄λμ€
class Student: Person {
}
// Teacherλ μλΈ ν΄λμ€(μμ ν΄λμ€) - μμλ°μ ν΄λμ€
class Teacher: Person {
}
let person: Person = Person() - κ°λ₯
let student: Student = Student() - κ°λ₯
let student: Person = Student() - κ°λ₯
let teacher: Person = Teacher() - κ°λ₯
let person: Student = Person() - λΆκ°λ₯
// λΆλͺ¨ ν΄λμ€μ μΈμ€ν΄μ€λ₯Ό μμ ν΄λμ€ νμ
μΌλ‘ ν λΉν μ μμ
let student: Teacher = Student() - λΆκ°λ₯
//Teacherμ Student ν΄λμ€ κ°μ μλ¬΄λ° κ΄κ³κ° μμ
νμ μ 체ν¬νλ μ°μ°μλ‘, λΉκ΅ κ²°κ³Όλ₯Ό bool νμ μ λ°ν
νμ 체νΉ
let char: Character = "A"
print(char is Character)
// μΆλ ₯κ°: true
print(char is String)
// μΆλ ₯κ°: false
μΈμ€ν΄μ€μ "νμ "μ νμΈνκ±°λ,Β ν΄λΉ μΈμ€ν΄μ€λ₯Ό μνΌ ν΄λμ€(λΆλͺ¨ ν΄λμ€)λ νμ ν΄λμ€(μμ ν΄λμ€)λ‘ μ·¨κΈνλ λ°©λ²
as
as
Β μ°μ¬μλ₯Ό μ¬μ©as?
μ΅μ
λ νμ
μ μΈμ€ν΄μ€λ₯Ό λ°ννκ³ , μ€ν¨νλ©΄Β nil
Β μ λ°νas!
class Person {
var id = 0
var name = "name"
var email = "hgk@gmail.com"
}
class Worker: Person {
// id
// name
// email
var salary = 300
}
class Programmer: Worker {
// id
// name
// email
// salary
var lang = "Swift"
}
// μ
μΊμ€ν
- as
let person1 = Person()
let worker1 = Worker()
let programmer1 = Programmer()
let personList = [person1, worker1, programmer1]
// νμ
μ μ μΈνμ§ μμμ§λ§ Person νμ
μΌλ‘ μΈμ -> μ¦ μ
μΊμ€ν
μ΄ λμμ
personList[1].name
//personList[1].salary -> Person νμ
μΌλ‘ λ³΄κ³ μκΈ° λλ¬Έμ salaryμ μ κ·Όνμ§ λͺ»ν¨
let worker2 = Worker()
worker2.salary
let workerPerson = worker2 as Person
//workerPerson.salary -> Person νμ
μΌλ‘ λ³΄κ³ μκΈ° λλ¬Έμ salaryμ μ κ·Όνμ§ λͺ»ν¨
// λ€μ΄μΊμ€ν
- as? / as!
// as?
let pro = programmer1 as? Programmer -> νμ
λ³νμ΄ λ μλ μκ³ μλ μλ μκΈ° λλ¬Έμ μ΅μ
λμ 리ν΄
if let person2 = programmer1 as? Programmer {
person2.lang
}
if let person3 = worker1 as? Programmer {
person3.lang
}
// as!
let pro2 = worker2 as! Programmer // Error : νμ
λ³ν μ€ν¨μ μ€λ₯
λλ¨Έμ§ λ΄μ©μ λ΄μΌ μ 리ν΄λ³΄κ² λ€!