-
Protocol 1편 (Protocol 정의 방법)오늘의 Swift 상식 2021. 8. 16. 18:19728x90반응형
안녕하세요. iOS 개발자 에이든입니다!👦🏻
이번 시간은 Protocol에 대해 알아보겠습니다!
이번 시간은 내용이 좀 많아요.
그래서 1,2편으로 진행해보려고 합니다.
바로 그냥 들어가시죠~
Protocol은 쉽게 말해 청사진이라고 볼 수 있어요.
Property나 Method를 정의하여 해당 Protocol을 채택하면
내부만 바로 구현을 하는거죠!
Protocol의 특징은 다음과 같습니다.
1. Struct, Class, Enum은 Protocol을 채택해서 특정 기능을 실행하기 위한 Protocol의 요구사항을 실제로 구현할 수 있습니다.
2. Protocol은 정의를 하고 제시를 할 뿐 스스로 기능을 구현하지는 않습니다. (조건만 정의)
3. 하나의 Type으로 사용되기 때문에 아래와 같이 Type 사용이 허용되는 모든 곳에 Protocol을 사용할 수 있습니다.
- Method, Initializer의 Parameter Type 혹은 Return Type
- 상수, 변수, Property의 Type
- Array, Dictionary의 원소Type
4. 기본 형태
protocol 이름 { // 정의 }
5. Struct, Class, Enum 등에서 Protocol을 채택하려면 Type 이름 뒤에 콜론“:”을 붙여준 후 채택할 Protocol 이름을 쉼표“,”로 구분하여 명시해주면 됩니다. (단, SubClass의 경우 SuperClass를 가장 앞에 명시해야합니다.)
struct SomeStruct: AProtocol, AnotherProtocol { // 정의 } // 상속받는 Class의 Protocol 채택 class SomeClass: SuperClass, AProtocol, AnotherProtocol { // 정의 }
자 그럼 이번에는 각 Component 별로 어떻게 정의를 하고 사용하는지 알아봅시다!
Property
Protocol에서는 Property가 저장 Property인지 연산 Property인지 명시하지 않고, 이름과 Type 그리고 gettable, settable한지 명시 합니다. (Property는 항상 var로 선언!!!)
protocol Student { var height: Double { get set } var name: String { get } static var schoolNumber: Int { get set } } class Aiden: Student { var roundingHeight: Double = 0.0 var height: Double { get { return roundingHeight } set { roundingHeight = 183.0 } } var name: String = "Aiden" static var schoolNumber: Int = 20112330 } let aiden = Aiden() print(aiden.height, aiden.name, Aiden.schoolNumber) // 0.0 Aiden 20112330 aiden.height = 183.0 print(aiden.height, aiden.name, Aiden.schoolNumber) // 183.0 Aiden 20112330
Method
1. Protocol에서는 Instance Method와 Type Method를 정의할 수 있습니다. 하지만 Method Patameter의 기본 값은 Protocol 안에서 사용할 수 없습니다.
2. Method를 정의할 때 이름과 반환값을 지정할 수 있고, {}는 적지 않습니다.
3. mutating 키워드를 사용해 Instance에서 변경 가능하다는 것을 표시할 수 있습니다. (값 타입에서만 사용 가능)protocol Person { static func breathing() func sleeping(time: Int) -> Bool mutating func running() } struct Aiden: Person { var heartRate = 100 static func breathing() { print("숨을 쉽니다") } func sleeping(time: Int) -> Bool { if time >= 23 { return true } else { return false } } mutating func running() { heartRate += 20 } } print(Aiden.breathing()) // 숨을 쉽니다. var aiden = Aiden() print(aiden.sleeping(time: 23)) // true print(aiden.heartRate) // 100 aiden.running() print(aiden.heartRate) // 120
Initializer
Protocol에서는 Initializer도 정의할 수 있으며 실패가능한 Initializer도 선언할 수 있습니다.
protocol SomeProtocol { init(someParameter: Int) } class SomeClass: SomeProtocol { // Protocol에서 특정 Initializer가 필요하다고 명시했기 때문에 구현할때 해당 Initializer에 required 키워드를 붙여줘야 합니다. required init(someParameter: Int) { // 구현부 } }
!! 특정 Protocol 의 Required Initializer를 구현하고, SuperClass의 Initializer를 SubClass에 상속하는 경우 SubClass의 이니셜라이저 앞에 required 키워드와 override 키워드를 붙여줘야 합니다.
protocol SomeProtocol { init() } class SomeSuperClass { init() { // 구현부 } } class SomeSubClass: SomeSuperClass, SomeProtocol { required override init() { // 구현부 } }
다음 시간에는 이어서 위임, 상속, 합성 등 Protocol을 활용하는 다양한 기능들에 대해 알아보겠습니다!
혹시라도 부족하거나 잘못된 부분 그리고 질문 있으시면 언제든 댓글 부탁드려요! 감사합니다!👦🏻👋🏻
728x90반응형'오늘의 Swift 상식' 카테고리의 다른 글
QR Code - 만들기편! (0) 2021.09.15 Protocol 2편 (Delegation, Extension, 상속, 합성) (0) 2021.08.25 Class의 상속 (0) 2021.08.15 Initializer 2편 (Class의 Initializer) (0) 2021.08.08 Initializer 1편 (Struct의 Initializer) (0) 2021.08.08