Search
Duplicate

Metatype(.Protocol)

생성일
2023/09/12 14:18
νƒœκ·Έ
Grammar

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 νƒ€μž…μ€ ν”„λ‘œν† μ½œμ„ μ±„νƒν•΄μ„œ κ΅¬ν˜„ν•˜λŠ” μ‹€μ œ νƒ€μž…μœΌλ‘œ μΆ”λ‘ λœλ‹€.

Β Reference