Protocols
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.
νλ‘ν μ½
- νΉμ μν μ μννκΈ° μν λ©μλ, νλ‘νΌν°, μ΄λμ λΌμ΄μ λ±μ μꡬμ¬νμ μ μ
- ꡬ쑰체, ν΄λμ€, μ΄κ±°νμ νλ‘ν μ½μ μ±ν(Adopted) ν΄μ νλ‘ν μ½μ μꡬμ¬νλ€μ ꡬν
- μ΄λ€ νλ‘ν μ½μ μꡬμ¬νμ λͺ¨λ λ°λ₯΄λ νμ μ κ·Έ νλ‘ν μ½μ μ€μνλ€(Conform) κ³ νν
- νμ
μμ νλ‘ν μ½μ μꡬμ¬νμ μΆ©μ‘±μν€λ €λ©΄ νλ‘ν μ½μ΄ μ μνλ κΈ°λ₯μ λͺ¨λ ꡬνν΄μΌ ν©λλ€. μ¦, νλ‘ν μ½μ κΈ°λ₯μ μ μνκ³ μ μ ν λΏμ΄μ§ μ€μ€λ‘ κΈ°λ₯μ ꡬννμ§λ μμ΅λλ€.
νλ‘ν μ½ μ μ - μꡬμ¬ν μ μ
protocol Talkable { // νλ‘ν μ½ μ μ
// νλ‘νΌν° μꡬ : νλ‘νΌν° μꡬλ νμ var ν€μλλ₯Ό μ¬μ©
var topic: String { get set }
var language: String { get }
// λ©μλ μꡬ
func talk()
// μ΄λμ
λΌμ΄μ μꡬ
init(topic: String, language: String)
}
νλ‘ν μ½ μ±ν - μꡬμ¬ν ꡬν
// Person ꡬ쑰체λ Talkable νλ‘ν μ½μ μ±ν
struct Person: Talkable {
// νλ‘νΌν° μꡬ μ€μ
var topic: String
let language: String
// λ©μλ μꡬ μ€μ
func talk() {
print("\(topic)μ λν΄ \(language)λ‘ λ§ν©λλ€")
}
// μ΄λμ
λΌμ΄μ μꡬ μ€μ
init(topic: String, language: String) {
self.topic = topic
self.language = language
}
}
'iOS π > Swift' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
Swift - κ³ μ°¨ν¨μ, Higher-order function (0) | 2021.02.10 |
---|---|
Swift19 - μ΅μ€ν μ (0) | 2021.02.10 |
Swift17 - assert/guard (0) | 2021.02.10 |
Swift16 - νμ μΊμ€ν (0) | 2021.02.10 |
Swift15 - Nil-Coalescing Operator (0) | 2021.02.03 |