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 |