You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
프로토콜이 존재하기 전에는 Flyable을 베이스 클래스로 해당 클래스와 관련된 클래스들이 이를 상속해서 다른 클래스를 만들었을 것.
하지만 POP에서는 모든 것이 프로토콜로 시작.
베이스 클래스 없이 기능 개념을 캡슐화할 수 있음.
타입을 정의할 때 전체적인 시스템을 훨씬 더 유연하게 만들 수 있음.
structFlappyBird:Bird,Flyable{letname:StringletflappyAmplitude:DoubleletflappyFrequency:DoubleletcanFly:BoolvarairsppedVelocity:Double{3* flappyFrequency * flappyAmplitude
}}structPenguin:Bird{letname:StringletcanFly:Bool=false}structSwiftBird:Bird,Flyable{varname:String{"Swift \(version)"}letcanFly:Bool=trueletversion:DoubleprivatevarspeedFactor=1000.0init(version:Double){self.version = version
}varairsppedVelocity:Double{
version * speedFactor
}}
canFly가 중복!
protocolBird{varname:String{get}}extensionBird{varcanFly:Bool{self is Flyable}}protocolFlyable{varairsppedVelocity:Double{get}}structFlappyBird:Bird,Flyable{letname:StringletflappyAmplitude:DoubleletflappyFrequency:DoublevarairsppedVelocity:Double{3* flappyFrequency * flappyAmplitude
}}structPenguin:Bird{letname:String}structSwiftBird:Bird,Flyable{varname:String{"Swift \(version)"}letversion:DoubleprivatevarspeedFactor=1000.0init(version:Double){self.version = version
}varairsppedVelocity:Double{
version * speedFactor
}}
Bird에 Extension으로 초기 구현을 해놓으면 canFly를 정의 해주지 않아도 모두 적용!
enumUnladenSwallow:Bird,Flyable{case african
case european
case unknown
varname:String{switchself{case.african:return"African"case.european:return"European"case.unknown:return"What do you mean? African or European?"}}varairspeedVelocity:Double{switchself{case.african:return10.0case.european:return9.9case.unknown:fatalError("You are thrown from the bridge of death!")}}}extensionUnladenSwallow{varcanFly:Bool{self!=.unknown
}}
기본 구현 재정의 가능!
protocolBird:CustomStringConvertible{varname:String{get}varcanFly:Bool{get}}extensionCustomStringConvertiblewhere Self:Bird{vardescription:String{
canFly ?"나는 날 수 있따!":"나는 날 수 업따!"}}
표준 라이브러리의 프로토콜을 채택하고 기본 구현도 가능!
classMotorcycle{init(name:String){self.name = name
speed =200.0}varname:Stringvarspeed:Double}protocolRacer{varspeed:Double{get} // speed is the only thing racers care about
}extensionFlappyBird:Racer{varspeed:Double{
airspeedVelocity
}}extensionSwiftBird:Racer{varspeed:Double{
airspeedVelocity
}}extensionPenguin:Racer{varspeed:Double{42 // full waddle speed
}}extensionUnladenSwallow:Racer{varspeed:Double{
canFly ? airspeedVelocity :0.0}}extensionMotorcycle:Racer{}letracers:[Racer]=[UnladenSwallow.african,UnladenSwallow.european,UnladenSwallow.unknown,Penguin(name:"penguin"),SwiftBird(version:5.1),FlappyBird(name:"flappy", flappyAmplitude:3.0, flappyFrequency:20.0),Motorcycle(name:"motorcycle")]extensionSequencewhere Iterator.Element ==Racer{func topSpeed()->Double{self.max(by:{ $0.speed < $1.speed })?.speed ??0.0}}
racers.topSpeed()