Upload
wileychoi
View
150
Download
1
Embed Size (px)
DESCRIPTION
Swift Protocols
Citation preview
Protocols
Swift
순서1. Protocols ?2. 프로토콜 문법3. 속성 요구사항4. 메소드 요구사항5. 변이 (mutating) 메소드6. 타입으로서의 프로토콜7. 위임 (Delegation)8. 확장을 프로토콜 일치에 추가9. 확장과 동시에 프로토콜 적용 선언10. 프로토콜타입의 콜렉션들11. 프로토콜 상속12. 프로토콜 합성13. 프로토콜 일치 확인하기14. 프로토콜 선택적 요구사항
Protocols
프로토콜은 전체적인 모습을 정의한다 .요구사항들의 구현을 직접 제공하지 않는다 .구현하는 쪽 (class 혹은 struct) 에서는 프로토콜의 요구사항을 충족시켜야 한다 .
프로토콜 문법// protocol 키워드를 사용합니다 .protocol SomeProtocol {
// 프로토콜 정의가 여기 온다}struct SomeStruct: FirstProtocol, AnotherProtocol {
// 구조체 정의가 여기 온다}class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
// 클래스 정의가 여기 온다 .}
속성 요구사항
protocol SomeProtocol {var mustBeSettable: Int { get set }var doesNotNeedToBeSettable: Int { get }
}protocol AnotherProtocol {
class var someTypeProperty: Int { get set }}
예제 1
메소드 요구사항
변이 (mutating) 메소드
타입으로서의 프로토콜
위임 (Delegation)
위임 (Delegation) #2
위임 (Delegation) #3
확장을 프로토콜 일치에 추가
확장과 동시에 프로토콜 적용 선언
프로토콜타입의 콜렉션들
프로토콜 상속
protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
// 프로토콜 정의가 여기 온다}
프로토콜 합성
프로토콜 일치 확인하기
is : 인스턴스가 프로토콜과 일치하면 true, 아니면 falseas : 강제로 다운캐스팅하고 실패하면 런타임 오류가 난다as? : 인스턴스가 프로토콜과 일치하지 않으면 nil 이 된다@objc : 일치확인을 위해 protocol 앞에 꼭 써줘야 한다
프로토콜 선택적 요구사항
optional 키워드를 사용하여 선택적으로 요구사항을 정의할 수 있다 .
@objc protocol CounterDataSource {optional func
incrementForCount(count: Int) -> Intoptional var fixedIncrement: Int { get
}}