Swift | Protocol Oriented Programming
程序员文章站
2022-04-06 15:06:25
...
原文
https://www.raywenderlich.com/148448/introducing-protocol-oriented-programming
Playground 笔记
protocol Bird: CustomStringConvertible{
var name: String { get }
}
protocol Flyable{
var airspeedVelocity: Double { get }
}
extension CustomStringConvertible where Self: Bird {
var description: String {
return canFly ? "I can fly" : "Guess I’ll just sit here :["
}
}
extension Bird{
var canFly: Bool {
return self is Flyable
}
}
struct FlappyBird: Bird, Flyable{
var airspeedVelocity: Double{
return 3 * flappyAmplitude * flappyFrequency
}
let flappyAmplitude: Double
let flappyFrequency: Double
let name: String
}
struct Penguin: Bird{
let name: String
}
struct SwiftBird: Bird, Flyable{
var name: String { return "Swfit \(version)" }
let version: Double
var airspeedVelocity: Double{
return version * 1000
}
}
enum UnladenSwallow: Bird, Flyable{
case african
case european
case unknown
var name: String{
switch self {
case .african:
return "African"
case .european:
return "European"
default:
return "Unknown"
}
}
var airspeedVelocity: Double{
switch self {
case .african:
return 10
case .european:
return 9
default:
return 0
}
}
}
extension UnladenSwallow{
var canFly: Bool{
return self != .unknown
}
}
UnladenSwallow.african
let numbers = [10, 20, 30, 40, 50]
let slice = numbers[1...3]
let reversedSlice = slice.reversed()
let answer = reversedSlice.map { $0 * 10 }
class Motorcycle{
var name: String
var speed: Double
init(name: String) {
self.name = name
speed = 200
}
}
protocol Racer{
var speed: Double { get }
}
extension FlappyBird: Racer{
var speed: Double{
return airspeedVelocity
}
}
extension SwiftBird: Racer{
var speed: Double{
return airspeedVelocity
}
}
extension Penguin: Racer{
var speed: Double{
return 42
}
}
extension UnladenSwallow: Racer{
var speed: Double{
return canFly ? airspeedVelocity : 0
}
}
extension Motorcycle: Racer {}
let racers: [Racer] = [
UnladenSwallow.african,
UnladenSwallow.european,
UnladenSwallow.unknown,
FlappyBird(flappyAmplitude: 3, flappyFrequency: 20, name: "Flappy Bird"),
SwiftBird(version: 3.0),
Penguin(name: "King Penguin"),
Motorcycle(name: "BMW Motorcycle")
]
extension Sequence where Iterator.Element == Racer{
func topSpeed() -> Double{
return self.max(by: { $0.speed < $1.speed })?.speed ?? 0
}
}
racers[1...3].topSpeed()
protocol Score: Equatable, Comparable{
var value: Int { get }
}
struct RacingScore: Score{
let value: Int
static func ==(lhs: RacingScore, rhs: RacingScore) -> Bool{
return lhs.value == rhs.value
}
static func <(lhs: RacingScore, rhs: RacingScore) -> Bool{
return lhs.value < rhs.value
}
}
RacingScore(value: 120) > RacingScore(value: 100)