λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
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