Reputation: 515
Note: This program is basically intended to print to the console output window, I also pasted the whole program so that it will not confuse whoever is answering my basic question.
Question: How is the 'didSet' observer working here, I'm very confused, What is the code: '? slowdown : speedup' after the code: '(speed > speedLimit)' for? and then it calls changeSpeed() at the end??
changeSpeed is simply an empty variable function, the whole didSet logic here is confusing especially that '?' before the code: 'slowdown: speedup'
class Vehicle {
var speed: Int
var speedLimit: Int {
willSet {
println("Preparing to change speed to \(newValue) MPH")
}
didSet {
var changeSpeed: () -> () = (speed > speedLimit) ? slowdown : speedup
while speed != speedLimit {
changeSpeed()
println("Now I'm driving \(speed) MPH because the speed limit changed to \(speedLimit) MPH from \(oldValue) MPH\n")
}
}
init(speedLimit: Int, speed: Int) {
self.speedLimit = speedLimit
self.speed = speed
println("Speed limit is \(speedLimit) MPH, I'm driving: \(speed) MPH") }
func speedup() {
println("Speeding up to \ \(--speed) MPH...")
}
}
let car = Vehicle(speedLimit: 65, speed: 65)
car.speedLimit = 55
car.speedLimit = 70
//sorry for any confusion but the didSet logic here completely threw me off and I'm getting more confused about the whole program?? I got this from a swift book.
Upvotes: 0
Views: 64
Reputation: 14824
? :
is called the ternary operator, and is used as condition ? valueIfTrue : valueIfFalse
. The line var changeSpeed: () -> () = (speed > speedLimit) ? slowdown : speedup
is equivalent to:
var changeSpeed: () -> ()
if speed > speedLimit {
changeSpeed = slowdown
} else {
changeSpeed = speedup
}
The logic in didSet
, therefore, essentially says:
Upvotes: 1