Last active
June 5, 2020 11:14
-
-
Save LeeKahSeng/f6e7642bf3a86e827fab779f57185497 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Flyable { | |
/// Limit the speed of flyable | |
var speedLimit: Int { get } | |
func fly() | |
} | |
extension Flyable { | |
func fly() { | |
print("Fly with speed limit: \(speedLimit)mph") | |
} | |
} | |
class Airplane: Flyable { | |
var speedLimit = 500 | |
} | |
class Helicopter: Flyable { | |
var speedLimit = 150 | |
} | |
class SpeedLimitUpdater { | |
static func reduceSpeedLimit(of flyables: [Flyable], by value: Int) { | |
// Only update speedLimit of Helicopter & Airplane | |
for flyable in flyables { | |
if let helicopter = flyable as? Helicopter { | |
helicopter.speedLimit -= value | |
} else if let airplane = flyable as? Airplane { | |
airplane.speedLimit -= value | |
} | |
} | |
} | |
static func increaseSpeedLimit(of flyables: [Flyable], by value: Int) { | |
// Only update speedLimit of Helicopter & Airplane | |
for flyable in flyables { | |
if let helicopter = flyable as? Helicopter { | |
helicopter.speedLimit += value | |
} else if let airplane = flyable as? Airplane { | |
airplane.speedLimit += value | |
} | |
} | |
} | |
} | |
class Bird: Flyable { | |
private(set) var speedLimit = 20 | |
} | |
// Let's test the code above | |
let flyable1 = Bird() | |
let flyable2 = Airplane() | |
let flyable3 = Helicopter() | |
let flyableArray: [Flyable] = [flyable1, flyable2, flyable3] | |
SpeedLimitUpdater.reduceSpeedLimit(of: flyableArray, by: 10) | |
for flyable in flyableArray { | |
flyable.fly() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a good example in terms of getter and setter according to pop