Metatype (.Protocol)
Β .Protocol : νλ‘ν μ½μ λ©ννμ μ μ‘°κΈ λ€λ₯΄λ€.
Humanμ΄λ νλ‘ν μ½μ λ§λ€ λ
protocol Human { }
let humanType: Human.Type = Human.self // Cannot convert value of type
Swift
볡μ¬
μ΄ νλ‘ν μ½μ λ©ννμ
μ μ»κΈ° μν΄
Human.Type μ΄λ νμ
μ λ³μ human Typeμ λ§λ€κ³ Human.selfλ₯Ό λ£μ΄μ£Όλ©΄ μλ¬κ° λ°μνλ€.
μλνλ©΄ Human.selfλ‘ μ»λ νλ‘ν μ½ μ체μ λ©ννμ
μ μ΄λ κ² μ μλμ§κ° μκΈ° λλ¬Έμ΄λ€.
μλ₯Όλ€λ©΄
struct Hj: Human { }
let hjType: Human.Type = Hj.self // Hj.Type
Swift
볡μ¬
Human.Typeμ ν κ²½μ°,
Human μ΄λ νλ‘ν μ½μ λ©ννμ
μ μκΈ°νλ κ²μ΄ μλλΌ,
ν΄λΉ νλ‘ν μ½μ λ°λ₯΄λ Hjμ λ©ννμ
μ μκΈ°νλ κ²μ΄ λμ΄λ²λ¦°λ€.
(μ΄λ₯Ό existential metatype μ΄λΌ λΆλ₯Έλ€)
λ°λΌμ μ§μ§ Humanμ΄λ νλ‘ν μ½μ λ©ννμ
μ μ»κ³ μΆλ€λ©΄
β .Protocol ν€μλλ₯Ό μ¬μ©νλ©΄ λλ€.
protocol Human { }
let humanType: Human.Protocol = Human.self // Human.Protocol
Swift
볡μ¬
μ΄λ κ² .Protocol μ μ΄μ©νλ©΄, νλ‘ν μ½μ λ©ννμ
μ μ»μ μ μλ€.
μ¬μ€ Type Annotationμ μλ΅νκ³ type(of:) λ©μλλ₯Ό ν΅ν΄μ λ΄λ
λ€μ λ©ννμ
μ΄ νλ λ λΆκΈ΄νλ€.
Human νλ‘ν μ½μ λ©ννμ
μ .Protocol μ΄ λ€μ΄κ°μΌ νλ€λ κ²μ μ μ μλ€.
νμ§λ§ .Protocol μ νμ
μμ κ±°μ μ¬μ©νλ μΌμ΄ μλ€κ³ νλ€.. γ
Β selfμ .selfμ Selfμ μ°¨μ΄
self μ .self μ Self μ μ°¨μ΄μ μ??
Β 1. self
self λ κ²μ μΈμ€ν΄μ€μμ μμ±λλ©°, ν΄λΉ μΈμ€ν΄μ€μ λν΄μ λνλΈλ€.
ν΄λμ€, ꡬ쑰체λ₯Ό λ§λ€ λ
class Human {
var name = "Hj"
func printName() {
print(self.name)
}
}
Swift
볡μ¬
μ΄λ self λ₯Ό μ¬μ©νλ€.
Β 2. .self
let tableView = UITableView()
tableView.register(HjCell.self, forReuseIdentifier: "HjCell")
Swift
볡μ¬
ν΄λΉ νμ
μ λ©ννμ
κ°μ μ»κΈ° μν λ μ¬μ©νλ€.
Β 3. Self
Self λ νλμ TypeμΌλ‘, νμ¬ μν μ½λμ Typeμ΄ Self μ Typeμ΄ λλ€.
extension Int {
static let zero: Int = 0
func makeZero() -> Int {
return Int()
}
}
Swift
볡μ¬
μ°λ¦¬κ° μμ κ°μ΄ Intνμ νμ₯νλ €κ³ ν λ,
λ¬Όλ‘ μμ²λΌ νλ‘νΌν° zeroμ νμ
, λ©μλ makeZeroμ λ°ν νμ
μ μ§μ Intλ‘ λͺ
μνμ¬λ λλ€.
κ·Έλ¬λ Self λ νμ¬ μν μ½λμ νμ
μ Self μ νμ
μ΄ λλ€.
νμ¬ λ΄ νμ
μ΄ Intμ΄κΈ° λλ¬Έμ, Self μ νμ
λν Int κ° λκ³
extension Int {
static let zero: Self = 0
func makeZero() -> Self {
return Self()
}
}
Swift
볡μ¬
μ΄λ κ² IntλΌλ νμ
λμ Self λ₯Ό μΈ μ μλ€.
Self μ μ₯μ ?
β’
νμ
μ μμ‘΄νμ§ μλ μ½λκ° λ μ μλ€.
β’
νλ‘ν μ½ λ΄μμ μ€μ νμ
λμ ν΄μ μ¬μ©νκΈ°λ νλ€.
β¦
μ΄ κ²½μ°, Self νμ
μ νλ‘ν μ½μ μ±νν΄μ ꡬννλ μ€μ νμ
μΌλ‘ μΆλ‘ λλ€.