Ali
Ali

Reputation: 515

didSet logic in this code is really confusing me, whats happening?

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

Answers (1)

andyvn22
andyvn22

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:

  1. We're going to change our speed. If we're above the speed limit, we'll be slowing down soon, otherwise, we'll be speeding up soon.
  2. Go ahead and change. Are we at the speed limit yet? If not, repeat this change until we have reached the speed limit.
  3. Every time we change the speed (see step 2), print a message about it.

Upvotes: 1

Related Questions