티스토리 뷰

출처

http://kka7.tistory.com/27




프로토콜

메소드, 프로퍼티, 특정 작업이나 기능에 적합한
다른 요구사항을 상세하게 정의한다.


문법

protocol SomeProtocol {

    

}


protocol AnotherProtocol: SomeProtocol {

    

}


protocol TheOtherProtocol : SomeProtocol, AnotherProtocol {

    

}




프로퍼티 요구사항

프로토콜은 프로퍼티가 저장 프로퍼티이거나 계산 프로퍼티인지 지정하지 않는다.
다만 필수 프로퍼티 이름과 타입, gettable, settable 인지 반드시 지정해야한다.

{ get set } 을 요구하는 프로토콜 프로퍼티가 존재한다면
상수 저장 프로퍼티 ( let a ), 읽기 전용 계산 프로퍼티 ( var a : Point { return b } ) 는
위 조건을 만족시킬 수 없다. 

protocol SomeProtocol {

    var mustBeSettable: Int { get set }

    var doesNotNeedToBeSettable: Int { get }

}


protocol AnotherProtocol {

    static var someTypeProperty: Int { get set }

}


protocol FullyNamed {

    var fullName: String { get }

}



구조체가 FullyNamed 를 구현하는 간단한 구조체 예제이다.

struct Person: FullyNamed {

    var fullName: String

}

let john = Person(fullName: "John Appleseed")

// john.fullName is "John Appleseed"



class 가 FullNameProtocol 을 구현하는 예제이다.


protocol FullNameProtocol {

    var fullName: String { get }

}


class Person: FullNameProtocol {

    var prefix: String

    var name: String

    init(_ prefix: String, _ name: String) {

        self.prefix = prefix

        self.name = name

    }

    

    var fullName: String {

        return "\(self.prefix) \(self.name)"

    }

}


var person = Person("Enterprise", "USS")

print(person.fullName)







메소드 요구사항

인스턴스 메소드와 타입 메소드를 요구할 수 있다.


protocol SomeProtocol {

    static func staticMethod()

    func instanceMethod()

}


class TestClass: SomeProtocol {

    static func staticMethod() {

        print("staticMethod")

    }

    

    func instanceMethod() {

        print("instanceMethod")

    }

}




Mutating 메소드 요구사항

mutating 은 struct, enum 에서 사용되는 것으로
class 에서 mutating method 를 구현해야할 때는 mutating 키워드를 사용하지 않는다.

protocol SomeProtocol {

    mutating func toggle()

}


enum EnumTest: SomeProtocol {

    case Off

    case On

    

    mutating func toggle() {

        switch self {

        case .On:

            self = .Off

        case .Off:

            self = .On

        }

    }

}


class ClassTest: SomeProtocol {

    func toggle() {

        print("toggle")

    }

}


var e = EnumTest.Off

e.toggle()







초기화 요구사항


프로토콜 타입을 준수해서 구현되도록 특정 초기화를 요구할 수 있다.

이 때 프로토콜을 준수하는 클래스에서는 required 키워드를 사용해야한다.



protocol SomeProtocol {

    init(someParameter: Int)

}


class SomeSuperClass: SomeProtocol {

    required init(someParameter: Int) {

        

    }

}


class SomeClass: SomeSuperClass, SomeProtocol {

    required override init(someParameter: Int) {

        

    }

}






Delegate 패턴, Protocol 상속

Objective C 와 동일하게 가능하다.





Class 전용 프로토콜


protocol SomeProtocol: class {

    func print()

}


class SomeClass:SomeProtocol {

    func print() {

        

    }

}






프로토콜 합성

2개의 요구사항을 따르는 것이 필요할 때
합성된 형식으로 사용할 수 있다.

protocol Named {

    var name: String { get }

}

protocol Aged {

    var age: Int { get }

}

struct Person: Named, Aged {

    var name: String

    var age: Int

}


func wishHappyBirthday(to celebrator: Named & Aged) {

    print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")

}


let birthdayPerson = Person(name: "Malcolm", age: 21)

wishHappyBirthday(to: birthdayPerson)





프로토콜 준수 체크

as? 를 이용해 체크가 가능하다.

if let hasNamed = birthdayPerson as? Named {

    print("true")

}




기본 구현 제공하기 (extension)

extension protocol 을 이용하여 기본적인 구현을 제공할 수 있다.

protocol SomeProtocol {

    func someMethod()

}

extension SomeProtocol {

    func someMethod() {

        print("someMethod")

    }

}


class SomeClass: SomeProtocol { }


let a = SomeClass()

a.someMethod()







'iOS 개발 > Swift' 카테고리의 다른 글

[Swift 3] ARC (Automatic Reference Counting)  (0) 2017.04.18
[Swift 3] 제네릭 (Generics)  (0) 2017.04.16
[Swift 3] 해제 (Deinitialization)  (0) 2017.04.15
[Swift 3] 초기화 (Initialzer)  (0) 2017.04.15
[Swift 3] 상속 (Inheritance)  (0) 2017.04.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함