νλ‘ν μ½ (Protocols)
- λ°λΌμΌνλ μꡬ μ¬νμ μ μνλ€.
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
- μμ± μμ : λΆλͺ¨ν΄λμ€ λ¨Όμ μμ±νκ³ κ·Έ λ€μμ νλ‘ν μ½μ μ±ννλ€.
protocol SomeProtocol {
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: Int { get }
}
- κ° νλ‘νΌν°κ° gettable μΈμ§ gettableκ³Ό settable μΈμ§ μ§μ ν΄μ€μΌ ν¨
mutating λ©μλ μꡬμ¬ν
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case off, on
mutating func toggle() { }
}
class Light: Togglable {
func toggle() { }
}
- μ΄κ±°νμ΄λ κ΅¬μ‘°μ²΄κ° νλ‘ν μ½μ μ±ν → mutating ν€μλ μμ±ν¨
- ν΄λμ€κ° νλ‘ν μ½ μ±ν → mutating ν€μλ μμ±ν νμμμ
protocol SomeProtocol {
init(someParameter: Int)
}
final class SomeClass: SomeProtocol {
required init(someParameter: Int) {
// initializer implementation goes here
}
}
- xcodeμμ λ°λ‘ μλμ μλ λ λ§μ½ finalν€μλκ° λΆμΌλ©΄ required λΆμ΄λκ² μλ―Έμμ (μμλ μΌμ΄ μκΈ°λλ¬Έμ μꡬ μμ±μλ₯Ό ꡬνν μΌλ μλ€)
protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
// protocol definition goes here
}
- νλ‘μ½μ½μ΄ νλ‘ν μ½μ μμν μ μμ
protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
// class-only protocol definition goes here
}
- AnyObject νλ‘ν μ½ μ±ννλ©΄ ν΄λμ€ μ μ© νλ‘ν μ½ λ§λ€ μ μμ
νλ‘ν μ½ νΌν©
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, \\(celebrator.name), you're \\(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)
- & ν€μλ (ex Named & Aged) (μ¬λ¬κ°λ κ°λ₯)
- & ν€μλλ‘ λ¬ΆμΈ νλ‘ν μ½μ μ±νν νμ μ λνλ
Optional Protocol μꡬμ¬ν
@objc protocol CounterDataSource {
@objc optional func increment(forCount count: Int) -> Int
@objc optional var fixedIncrement: Int { get }
}
- νλ‘ν μ½ μμ μ μΈλμ΄ μλ νλ‘νΌν° / λ©μλλ λͺ¨λ required μ¦, νμμ μΈ κ²
- κΌ κ΅¬ννμ§ μμλ λλ νλ‘νΌν°λ λ©μλλ₯Ό λ§λ€κ³ μΆμ λ μ΅μ λ νλ‘ν μ½ μ¬μ©
- νλ‘ν μ½κ³Ό μ΅μ
λ μꡬμ¬νμ λͺ¨λ @objc μμ±μΌλ‘ νμλμ΄μΌνλ€.
- μ΅μ λ νλ‘ν μ½μ ν΄λμ€λ§ μ¬μ© (ꡬ쑰체, μ΄κ±°ν x)
- Objective-Cμμ νλ‘ν μ½μ μ€λ‘μ§ "ν΄λμ€ μ μ©"μμλ§ μ±ννκΈ° λλ¬Έ
'Swift Language Guide' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[Swift Language Guide] ARC (0) | 2023.09.07 |
---|---|
[Swift Language Guide] ꡬ쑰체μ ν΄λμ€ (Structures and Classes) (0) | 2023.06.05 |
[Swift Language Guide] μ΄κ±°ν (Enumerations) (0) | 2023.06.05 |
[Swift Language Guide] ν΄λ‘μ (Closures) (0) | 2023.06.05 |
[Swift Language Guide] ν¨μ(Functions) (0) | 2023.05.24 |