๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
iOS ๐ŸŽ/Swift

Swift18 - ํ”„๋กœํ† ์ฝœ

by yongmin.Lee 2021. 2. 10.

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