iOS/🟠 Swift

[Swift] ν”„λ‘œν† μ½œ κ°œμš” (Protocol Overview)

woozzang 2021. 1. 15. 14:13
참고 자료: Protocols - swift.org

 

κ°œμš”

ν”„λ‘œν† μ½œμ€ μš”κ΅¬μ‚¬ν•­μž…λ‹ˆλ‹€.

 

ν”„λ‘œν† μ½œμ—λŠ” κ΅¬ν˜„ν•΄μ•Όν•˜λŠ” λ©€λ²„λ“€μ˜ λͺ©λ‘μ΄ λ‚˜μ—΄λ˜μ–΄ μžˆμŠ΅λ‹ˆλ‹€.

 

ν”„λ‘œν† μ½œμ„ μ±„μš©ν•œ ν˜•μ‹μ€ μš”κ΅¬μ‚¬ν•­μ„ λ°˜λ“œμ‹œ λͺ¨λ‘ κ΅¬ν˜„ν•΄μ•Ό ν•©λ‹ˆλ‹€.

" When you adopt protocol, you should conform to protocol."

 

이것을 Adopting Protocol 이라고 ν•˜λ©° `ν”„λ‘œν† μ½œμ„ λ”°λ₯Έλ‹€`, `ν”„λ‘œν† μ½œμ„ μ±„μš©ν•œλ‹€` 라고 ν‘œν˜„ν•©λ‹ˆλ‹€.

 

ν”„λ‘œν† μ½œμ—λŠ” κ΅¬ν˜„ λ‚΄μš©μ€ λ“€μ–΄κ°€ μžˆμ§€ μ•Šκ³ , μ±„μš©ν•œ νƒ€μž…μ΄ 직접 κ΅¬ν˜„μ„ ν•©λ‹ˆλ‹€.

 

ν”„λ‘œν† μ½œμ€ ν”„λ‘œν† μ½œ κ°„ 상속을 μ§€μ›ν•˜λ©°, ν΄λž˜μŠ€μ™€ 달리 닀쀑 상속도 μ§€μ›ν•©λ‹ˆλ‹€.

즉, ν•˜λ‚˜μ˜ ν”„λ‘œν† μ½œμ€ μ—¬λŸ¬κ°œμ˜ ν”„λ‘œν† μ½œμ„ λ™μ‹œμ— 상속받을 수 μžˆμŠ΅λ‹ˆλ‹€.

 

enum, struct, class κ°€ ν”„λ‘œν† μ½œμ„ 채택할 수 μžˆμŠ΅λ‹ˆλ‹€.


 

Syntax

protocol Something {
    func doSomething()
}

//Adopting Protocols
struct Size: Something {
    func doSomething() {
        // code
    }
}

 

classκ°€ μ„œλΈŒν΄λž˜μ‹±ν•˜λ©΄μ„œ ν”„λ‘œν† μ½œλ„ μ±„μš©ν•˜λŠ” 경우, SuperClassλ₯Ό λ¨Όμ € λ‚˜μ—΄ν•©λ‹ˆλ‹€.

 

ν”„λ‘œν† μ½œ μš”κ΅¬μ‚¬ν•­ 쀑 λ©”μ†Œλ“œλ₯Ό κ΅¬ν˜„ν•  μ‹œ, λ©”μ„œλ“œ ν—€λ“œλ§Œ ν”„λ‘œν† μ½œκ³Ό λ˜‘κ°™μ΄ κ΅¬ν˜„ν•˜λ©΄ λ©λ‹ˆλ‹€.

 

즉, λ©”μ†Œλ“œ λ°”λ””λŠ” 자유둭게 κ΅¬ν˜„ν•΄λ„ λ©λ‹ˆλ‹€.


 

Class-Only Protocol

클래슀만 μ±„μš©κ°€λŠ₯ν•œ ν”„λ‘œν† μ½œμ„ λ§Œλ“€μ–΄ 쀄 수 μžˆμŠ΅λ‹ˆλ‹€.

 

μ„Έλ―Έμ½œλ‘  뒀에 `AnyObject` λ§Œ λΆ™μ—¬μ£Όλ©΄ λ©λ‹ˆλ‹€.

 

//Class-Only Protocols
protocol SomethingObject: AnyObject, Something {
    
}

//  struct Value: SomethingObject {
//    μ—λŸ¬ λ©”μ‹œμ§€ ( Class-Only Protocols μ±„μš© μ‹œλ„ )
//  }

class Object: SomethingObject {
    func doSomething(){
        
    }
}

 

 

Class-Only Protocol μ±„μš© μ‹œ

 

 

μœ„ μ½”λ“œμ—μ„œ SomethingObject ν”„λ‘œν† μ½œμ€ Class-Only Protocolμž…λ‹ˆλ‹€.

 

이 ν”„λ‘œν† μ½œμ„ ꡬ쑰체가 μ±„μš©ν•  μ‹œ 컴파일 μ—λŸ¬κ°€ λ‚©λ‹ˆλ‹€.

 

 

 

끝!


πŸ€–πŸŸ’[우짱의 iOS λΈ”λ‘œκ·Έ]πŸ”΅πŸ’»

iOSλ₯Ό κ³΅λΆ€ν•˜λ©΄μ„œ 배운 λ‚΄μš©μ„ κΈ°λ‘ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.

 

 

λ‹€μŒ κΈ€: Property Requirements - Protocol

 

Property Requirements - Protocol

var ν”„λ‘œν† μ½œμ—μ„œ `var` ν‚€μ›Œλ“œλŠ” μ†μ„±μ˜ κ°€λ³€μ„± κ³ΌλŠ” 관련이 μ—†μŠ΅λ‹ˆλ‹€. varλŠ” 단지 이것이 ν”„λ‘œν† μ½œ μš”κ΅¬μ‚¬ν•­ 쀑 μ†μ„±μ΄λΌλŠ” κ²ƒλ§Œ κ°€λ¦¬ν‚΅λ‹ˆλ‹€. μ†μ„±μ˜ κ°€λ³€μ„± μ€ λ³€μˆ˜ 의 νƒ€μž… 뒀에 λΆ™λŠ” { get set }

woozzang.tistory.com