19
Protocols Swift

Swift protocols

Embed Size (px)

DESCRIPTION

Swift Protocols

Citation preview

Page 1: Swift protocols

Protocols

Swift

Page 2: Swift protocols

순서1. Protocols ?2. 프로토콜 문법3. 속성 요구사항4. 메소드 요구사항5. 변이 (mutating) 메소드6. 타입으로서의 프로토콜7. 위임 (Delegation)8. 확장을 프로토콜 일치에 추가9. 확장과 동시에 프로토콜 적용 선언10. 프로토콜타입의 콜렉션들11. 프로토콜 상속12. 프로토콜 합성13. 프로토콜 일치 확인하기14. 프로토콜 선택적 요구사항

Page 3: Swift protocols

Protocols

프로토콜은 전체적인 모습을 정의한다 .요구사항들의 구현을 직접 제공하지 않는다 .구현하는 쪽 (class 혹은 struct) 에서는 프로토콜의 요구사항을 충족시켜야 한다 .

Page 4: Swift protocols

프로토콜 문법// protocol 키워드를 사용합니다 .protocol SomeProtocol {

// 프로토콜 정의가 여기 온다}struct SomeStruct: FirstProtocol, AnotherProtocol {

// 구조체 정의가 여기 온다}class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {

// 클래스 정의가 여기 온다 .}

Page 5: Swift protocols

속성 요구사항

protocol SomeProtocol {var mustBeSettable: Int { get set }var doesNotNeedToBeSettable: Int { get }

}protocol AnotherProtocol {

class var someTypeProperty: Int { get set }}

Page 6: Swift protocols

예제 1

Page 7: Swift protocols

메소드 요구사항

Page 8: Swift protocols

변이 (mutating) 메소드

Page 9: Swift protocols

타입으로서의 프로토콜

Page 10: Swift protocols

위임 (Delegation)

Page 11: Swift protocols

위임 (Delegation) #2

Page 12: Swift protocols

위임 (Delegation) #3

Page 13: Swift protocols

확장을 프로토콜 일치에 추가

Page 14: Swift protocols

확장과 동시에 프로토콜 적용 선언

Page 15: Swift protocols

프로토콜타입의 콜렉션들

Page 16: Swift protocols

프로토콜 상속

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {

// 프로토콜 정의가 여기 온다}

Page 17: Swift protocols

프로토콜 합성

Page 18: Swift protocols

프로토콜 일치 확인하기

is : 인스턴스가 프로토콜과 일치하면 true, 아니면 falseas : 강제로 다운캐스팅하고 실패하면 런타임 오류가 난다as? : 인스턴스가 프로토콜과 일치하지 않으면 nil 이 된다@objc : 일치확인을 위해 protocol 앞에 꼭 써줘야 한다

Page 19: Swift protocols

프로토콜 선택적 요구사항

optional 키워드를 사용하여 선택적으로 요구사항을 정의할 수 있다 .

@objc protocol CounterDataSource {optional func

incrementForCount(count: Int) -> Intoptional var fixedIncrement: Int { get

}}