Swift 프로그래밍 - 377쪽 ~
프로토콜 : 특정 역할(기능)을 하기 위한 메서드, 프로퍼티, 기타 요구사항의 청사진을 정의한 것
프로토콜은 기능을 정의하고 제시할 뿐, 스스로 기능을 구현하는 것이 아니다.
스위프트에서 프로토콜은 완전한 하나의 타입으로 사용된다.
: protocol
키워드를 사용해 선언한다.
protocol 프로토콜이름 {
프로토콜 정의
}
프로퍼티 요구사항
var
로 선언{ get }
) 으로 할지, 읽고 쓰기({ get, set }
)로 할지 정해줘야 함static
키워드를 사용해 선언protocol SomeProtocol {
var settableProperty: String { get set }
var notNeedToBeSettableProperty: String { get }
static var typeProperty: Int { get }
}
메서드 요구사항
static
키워드 사용protocol Sendable {
var from: Sendable { get }
func send(data: Any)
static func isSendableInstance(_ instance: Any) -> Bool
}
가변 메서드 요구 mutating method requirements
protocol Resettable {
mutating func reset()
}
struct Point: Resettable {
var x: Int = 0
var y: Int = 0
mutating func reset() {
self.x = 0
self.y = 0
}
}
이니셜라이저 요구
required
키워드를 붙인 요구 이니셜라이저로 구현한다.required
를 생략 가능함required override
를 모두 명시해야 함protocol Name {
var name: String { get }
init(name: String)
}
class Person: Named {
var name: String
required init(name: String) {
self.name = name
}
}
struct SomeStruct: AProtocol, AnotherProtocol {
}
protocol Readable {
func read()
}
protocol Writeable {
func write()
}
protocol ReadWriteSpeakable: Readable, Writeable {
func speak()
}
class
키워드를 추가하면, 프로토콜이 클래스 타입에만 채택될 수 있도록 제한할 수 있다.class
키워드를 넣어야 한다.protocol ClassOnlyProtocol: class, Readable, Writeable {
// 이 프로토콜은 클래스에서만 채택 가능
}
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
func celebrateBirthday(to celebrator: Named & Aged) {
print("Happy Birthday \(celebrator.name)! Now you ard \(celebrator.age)")
}
class Car: Named {
var name: String
init(name: String) {
self.name = name
}
}
var someVariable: Car & Named
타입캐스팅의 is, as 연산자로 대상이 프로토콜을 준수하는지 확인하거나, 특정 프로토콜로 캐스팅할 수 있다.
is
: 해당 인스턴스가 프로토콜을 준수하는지 확인as?
: 다른 프로토콜로 다운캐스팅 시도as!
: 다른 프로토콜로 강제 다운캐스팅struct Person: Named, Aged {
var name: String
var age: Int
}
let bibi: Person = Person(name: "bibi", age: 99)
print(bibi is Named) // true
print(bibi is Aged) // true
if let castedInstance: Name = bibi as Named {
print("\(castedInstance) is Named")
} // Person is Named
...Delegate
"와같은 이름으로 정의되어 있다.UITableView
타입의 인스턴스가 할 일을 위임받아 처리하는 인스턴스는 UITableViewDelegate
프로토콜을 준수해야 함