Skip to content

Instantly share code, notes, and snippets.

@LeeKahSeng
Last active June 5, 2020 11:14
Show Gist options
  • Save LeeKahSeng/f6e7642bf3a86e827fab779f57185497 to your computer and use it in GitHub Desktop.
Save LeeKahSeng/f6e7642bf3a86e827fab779f57185497 to your computer and use it in GitHub Desktop.
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()
}
@seyitcodeit
Copy link

a good example in terms of getter and setter according to pop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment