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, 아니면 false
as : 강제로 다운캐스팅하고 실패하면 런
타임 오류가 난다
as? : 인스턴스가 프로토콜과 일치하지
않으면 nil 이 된다
@objc : 일치확인을 위해 protocol 앞에
꼭 써줘야 한다
프로토콜 선택적 요구사항
optional 키워드를 사용하여 선택적으로
요구사항을 정의할 수 있다 .
@objc protocol CounterDataSource {
optional func
incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int
{ get }
}

Swift protocols