프로토콜은 메서드, 프로퍼티, 그리고 특정 작업이나 기능의 부분이 적합한 다른 요구사항의 청사진을 정의한다. 해당 요구사항 구현을 위해 프로토콜은 클래스, 구조체, 열거형에 의해서 채택될 수 있다. 그리고 이 요구사항을 충족하는 모든 타입은 프로토콜을 준수한다고 말한다.
protocol SomeProtocol {
//프로토콜 내용 입력
}
struct SomeStructure : FirstProtocol, AnotherProtocol {
//구조체 정의 입력
}
//사용자 정의 타입은 콜론으로 구분된 타입 이름뒤에 프로토콜의 이름을 위치시켜 준수할 프로토콜을 채택한다.
class SomeClass : SomeSuperClass, FirstProtocol, SecondProtocol {
//클래스 정의 입력
}
//클래스가 상위 클래스를 상속하는 경우 채택한 모든 프로토콜 전에 상위 클래스 이름을 위치시킨다
protocol SomeProtocol {
var mustBeSettable : Int {get set}
var doesNotNeedToBeSettable : Int {get}
}
protocol AnotherProtocol {
static var someTypeProperty : Int { get set }
}
//다음과 같은 경우 타입 프로퍼티를 프로토콜 요구사항으로 가지는 경우이다.
protocol : SomeProtocol {
static func someTypeMethod()
}
//위 프로토콜은 타입 메서드 준수를 요구한다.
protocol RandomNumberGeterator {
func random() -> Double
}
//단일 인스턴스 메서드 요구사항을 가지는 프로토콜 또한 정의한 상태이다.
class LinearCongrautiaGenerator : RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29830.0
func random() -> Double {
lastRandom = ((lastRandom * a + c)
return lastRandom / m
}
}
//다음의 클래스는 두번째 프로토콜을 준수하고 해당 인스턴스 메서드를 구현해주어 잘 준수된 상태이다.
protocol Toggleable {
mutating func toggle()
}
//구조체나 열거형에 대해 Togglable 프로토콜을 구현하면 해당 구조체 또는 열거형은
//mutating으로 펴시된 toggle() 메서드 구현을 제공하는 프로토콜 준수가 가능하다.
enum OnOffSwitch : Togglable {
case off, on
mutating func toggle() {
switch self {
case .off:
self = .on
case .on:
self = .off
}
}
}
var lightSwitch = OnOffSwitch.off
lightSwitch.toggle()
// 이젠 해당 값이 .on으로 변경되었다.
protocol SomeProtocol {
init(someParameter : Int)
}
class SomeClass : SomeProtocol {
required init(someParameter : Int) {
//프로토콜 초기화 정의
}
}
//다음 required수식어를 사용할 경우 준수하는 클래스의 모든 하위 클래스도 해당 프로토콜의 초기화를 구현해야 한다.
//final클래스는 하위클래스가 없으므로 final로 표시된 클래스에는 required 수식어를 프로토콜 초기화 구문 구현에 표시할 필요가 없다.
protocol SomeProtocol {
init()
}
class SomeSuperClass {
init() {
//
}
}
class SomeSubClass : SomeSuperClass, SomeProtocol {
//"required" from protocol, "override" from superclass
required override init() {
//생성자를 정의해준다
}
}
//다음과 같이 하위클래스에서 프로토콜에서 요구되는 생성자와 함께 수퍼클래스의 생성자를 재정의할때는 키워드를 위와같이 작성해준다.