Smart Device/Swift

Swift protocol

언덕너머에 2014. 7. 3. 16:02

- protocol 

다수위 클래스들이 공통으로 사용할 수 있는 매서드를 묶어 클래스에 적용하는 것을 말한다.


protocol을 선언하기 위해서는 키워드 'protocol'을 사용한다.

protocol ExampleProtocol {

    var simpleDescription: String { get }

    mutating func adjust()

}


classes, enumerations, stucts는 protocol을 모두 적용할 수 있다.

class SimpleClass: ExampleProtocol {

    var simpleDescription: String = "A very simple class."

    var anotherProperty: Int = 69105

    func adjust() {

        simpleDescription += "  Now 100% adjusted."

    }

}

var a = SimpleClass()

a.adjust()

let aDescription = a.simpleDescription

 

struct SimpleStructure: ExampleProtocol {

    var simpleDescription: String = "A simple structure"

    mutating func adjust() {

        simpleDescription += " (adjusted)"

    }

}

var b = SimpleStructure()

b.adjust()

let bDescription = b.simpleDescription


구조체를 수정하는 매서드를 표시하는 simpleStructure의 선언에서 키워드 'mutating'의

사용에 유의하라. simpleClass의 선언에서 Class는 항상 매서드가 Class 내부를 수정할 수 있기에

키워드 'mutating'으로 표시된 매서드가 필요없다.


- extension

기존 형식에 새로운 기능(매서드나  계산된 속성)을 추가하기 위해서는 키워드 'extension'을 사용한다. 

extension은 다른곳에서 선언된 형식에 protocol 준수를 추가하기 위해 심지어 라이브러리나 프레임워크에서 

가져온 타입에도 사용할 수 있다.

 extension Int: ExampleProtocol {

    var simpleDescription: String {

    return "The number \(self)"

    }

    mutating func adjust() {

        self += 42

    }

}

7.simpleDescription