티스토리 뷰

Swift & objc

swift protocols

rhinoPHS 2018. 3. 14. 14:32





Protocols

- What

A protocol defines a blueprint of methods, properties, and other requirements that 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.


프로토콜은 class와 sturct, enum에 적용돼 요구사항의 실제 구현을 제공 할 수 있습니다.

-> 프로토콜은 청사진만 제공할 뿐 실제 구현을 하지 않습니다. class와 struct, enum등에서 구현을 해서 써야 합니다.


Any type that satisfies the requirements of a protocol is said to conform to that protocol

프로토콜에 요구사항을 만족하는 모든 타입은 프로토콜을 따른다라고 한다.


In addtion to spectifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionalliy that conforming types can take advantage of


프로토콜을 따르는 타입이 필수적으로 구현해야하는 요구사항 외에도 프로토콜을 확장하여 요구사항 중 일부를 구현할 수 있도 있고 그 타입이 활용할 수 있는 추가 기능도 구현할 수 있습니다.


-> 나중에 정리할 extension을 쓰면 프로 프로토콜을 확장해서 구현할 수 있습니다. 공부 하면서 여기 찾아보니까 swift의 꽃이라고 하더군요. 잘 배워야 할 것 같습니다. 또한 프로토콜을 따르는 class 등이 자기가 필요한 것을 따로 정의해서 사용할 수 있습니다. 프로토콜이 요구하는 사항만 잘 지키면 됩니다. 








- How

You define protocols in a very similar way to classes, structures, and enumerations

프로토콜 문법은 클래스, 구조체, 열거형을 선언하는 것과 비슷합니다.


protocol 프로토콜이름 {

    // 요구사항 정의

}


struct나 class에 사용할 때는 해당 객체 이름 앞에 colon(:)을 붙여주고 프로토콜을 comma(,)로 구분하여 나열해줍니다.


struct someStruct: 로토콜1, 로토콜2 {

    // 요구사항 구현

}


class 상속을 받을 때는 상위클래스이름을 맨 앞에다가 써야줘야 합니다.


class 클래스이름 : 상위클래스이름, 프로토콜1, 프로토콜2{

    // 요구사항 구현

}



- 프로퍼티 요구


A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn’t specify whether the property should be a stored property or a computed property—it only specifies the required property name and type. The protocol also specifies whether each property must be gettable or gettable and settable.


- 프로퍼티 요구 : 프로토콜은 클래스, 구조체, 열거형에 instance or type 프로퍼티를 요구할 수 있습니다. 포로토콜은 프로퍼티가 strored property 나 computed property가 돼야 한다고 명시하지 않습니다. 그저 이름과 타입을 요합니다. 또한 프로퍼티가 이 gettable한지 혹인 gettable & settable한지는 꼭 명시해한다.


Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.


- 프로퍼티 요구는 항상 var 로 선언 해야 한다. gettable과 settable 프로터티는 { get } { set }으로 나타내고 gettable은 { get} 으로 나타낸다.


- 사실 윗 문장이 잘 이해가 안 가서 정리를 해봤습니다. 인스턴스프로퍼티 사용


protocol testProtocol {

    // strored property로 하든 computed property 하든

    // get과 set 둘 다 돼야 한다!

    var mustBeSettableAngGetterable:Int { get set }

    

    // strored property로 하든 computed property 하든

    // get만 되면 된다. set은 되도 되고 안 되도 되고

    var doesNotNeedBeSettable:Int  get }

}


// strored version

// 각 속성을 stored로 했습니다

// storeed는 읽고 쓰기 즉 get과 set이 가능합니다.

// 따라서 testProtocol을 comfort합니다.

struct storedVersion: testProtocol{

    var mustBeSettableAngGetterable: Int

    var doesNotNeedBeSettable: Int

}


// computed version

// 각 속성을 computed로 했습니다

// read only computed로 선언 했습니다.

// 그랬더니 testProtocol을 따르지 않는다고 나옵니다.

// 왜냐하면 doesNotNeedBeSettable은 get만 되면 되니 문제가 없는데

// mustBesettableAndGetteable set아 돼야'만'합니다.

// 근데 set을 못하는 read only라서 does not conform라고 에러가 납니다.

struct computedVersion:testProtocol{

    var doesNotNeedBeSettable: Int {

        get{

            return 1

        }

//        set{

//            doesNotNeedBeSettable = 1

//        }


    }

    

    var mustBeSettableAngGetterable: Int{

        get{

            return 1

        }

        

//        set(newValue){

//            mustBeSettableAngGetterable = newValue

//        }

    }

}


- 또, 프로토콜 프로퍼티를 아래와 같이 선언 했더니.  'let' declarations cannot be computed properties 이렇게 나옵니다.

protocol sdfsd {

    let a:Int { get } // 

}


- 프로토콜의 프로퍼티는 다 computed 프로퍼티인가 봅니다. 그래서 var만 써야 하나봅니다.

computed property는 실제로 값을 저장 하지 않으니까 let을 못 쓰지요?


- 그리고 타입프로퍼티 사용

Always prefix type property requirements with the static keyword when you define them in a protocol.



- 항상 prefix type property는static keyword를 요구합니다. 그것들을 protocl에서 정의할 때

 이런 식으로 말이죠

protocol AnotherProtocol {

    static var someTypeProperty: Int { get set }

}


This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:

- 이 룰은 적용됩니다. 심지어 타입 프로퍼티 요구사항이 class나 static을 접두어로 사용하더라도 클래스에서 구현 될 때

 이런 식으로 말이죠.

class clsssConform:AnotherProtocol{

    static var someTypeProperty: Int = 100 // 타입프로퍼티는 초기화를 하거나 get set을 써야함

}


흠... 근데 protocol에서도 class type property도 지원 하는 건가? class type property는 class끼리의 상속을 위한 것 아닌가 안되는데 아래 처럼 하면 class properties are only allowed within classes 라고 하는데...

protocol classTypePropertyP{

    class var classTypeProperty: Int { get set }

}


하 바보 같았다...

protocol AnotherProtocol {

    static var someTypeProperty: Int { get }

}


class clsssConform:AnotherProtocol{

    class var someTypeProperty: Int {

        return 10

    }

//    class 타입 프로퍼티는 인스턴스에 값이 저장되는게 아니라서 computed property 로 선언해야 합니다.

}



- When

- Where

- Why



protocol은 class struct enum 에게 프로퍼티, 메소드, 뮤테이팅메소드, 이니셜라이져를 요구할 수 있다

더 알아볼 것

Protocol as Types, Delegation, Adding Protocol Conformance with and Extension, Collections of Protocol Types, Protocol Inheritance, Class Only Protocols, Protocol COmposition, Checking for Protocol Requirements, Protocol Extension



흠... 이렇게 정리하면 안 되겠다. 너무 오래 걸린다. 내가 쓴 것만... 쭉 한 번 봐야 하긴 하는데...












'Swift & objc' 카테고리의 다른 글

swift unit test  (0) 2018.03.19
피드백 정리  (0) 2018.03.19
typealias, Tuple  (0) 2018.03.16
swift type properties  (0) 2018.03.15
swift guard, if 기준정하기  (0) 2018.03.14
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함