[Swift 3] 프로토콜 (Protocols)
출처
프로토콜
문법
protocol SomeProtocol {
}
protocol AnotherProtocol: SomeProtocol {
}
protocol TheOtherProtocol : SomeProtocol, AnotherProtocol {
}
프로퍼티 요구사항
protocol SomeProtocol {
var mustBeSettable: Int { get set }
var doesNotNeedToBeSettable: Int { get }
}
protocol AnotherProtocol {
static var someTypeProperty: Int { get set }
}
protocol FullyNamed {
var fullName: String { get }
}
struct Person: FullyNamed {
var fullName: String
}
let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed"
class 가 FullNameProtocol 을 구현하는 예제이다.
protocol FullNameProtocol {
var fullName: String { get }
}
class Person: FullNameProtocol {
var prefix: String
var name: String
init(_ prefix: String, _ name: String) {
self.prefix = prefix
self.name = name
}
var fullName: String {
return "\(self.prefix) \(self.name)"
}
}
var person = Person("Enterprise", "USS")
print(person.fullName)
메소드 요구사항
protocol SomeProtocol {
static func staticMethod()
func instanceMethod()
}
class TestClass: SomeProtocol {
static func staticMethod() {
print("staticMethod")
}
func instanceMethod() {
print("instanceMethod")
}
}
Mutating 메소드 요구사항
protocol SomeProtocol {
mutating func toggle()
}
enum EnumTest: SomeProtocol {
case Off
case On
mutating func toggle() {
switch self {
case .On:
self = .Off
case .Off:
self = .On
}
}
}
class ClassTest: SomeProtocol {
func toggle() {
print("toggle")
}
}
var e = EnumTest.Off
e.toggle()
초기화 요구사항
프로토콜 타입을 준수해서 구현되도록 특정 초기화를 요구할 수 있다.
이 때 프로토콜을 준수하는 클래스에서는 required 키워드를 사용해야한다.
protocol SomeProtocol {
init(someParameter: Int)
}
class SomeSuperClass: SomeProtocol {
required init(someParameter: Int) {
}
}
class SomeClass: SomeSuperClass, SomeProtocol {
required override init(someParameter: Int) {
}
}
Delegate 패턴, Protocol 상속
Class 전용 프로토콜
protocol SomeProtocol: class {
func print()
}
class SomeClass:SomeProtocol {
func print() {
}
}
프로토콜 합성
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)
프로토콜 준수 체크
if let hasNamed = birthdayPerson as? Named {
print("true")
}
기본 구현 제공하기 (extension)
protocol SomeProtocol {
func someMethod()
}
extension SomeProtocol {
func someMethod() {
print("someMethod")
}
}
class SomeClass: SomeProtocol { }
let a = SomeClass()
a.someMethod()