Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy function in Swift

Could anyone tell me why in this 'odd' code (I'm having fun with Swift ;D) in lazy functions runEngine and stopEngine, print method is never executed? (please run this code in playground).

Thanks!

protocol EngineDelegate {
    func engineDidStart()
    func engineDidStop()
}

class Engine {

    var delegate: EngineDelegate?
    lazy var runEngine : () -> () = {
        print("Engine has been started")
        self.delegate?.engineDidStart()
    }
    lazy var stopEngine : () -> () = {
        print("Engine has been stoped")
        self.delegate?.engineDidStop()
    }

}

class Car: EngineDelegate {
    let engine = Engine()
    init() {
        engine.delegate = self
    }
    func engineDidStop() {
        print("MyOwnStop")
    }

    func engineDidStart() {
        print("MyOwnStart")
    }
}

let car = Car()

car.engine.runEngine()
like image 443
EvIld95 Avatar asked Jun 15 '26 23:06

EvIld95


1 Answers

The code runs as expected for me. enter image description here

At first I thought that the lazy modifier was unnecessary but it is. When Engine is instantiated, its delegate is nil and that value is what is captured by the closure. Using lazy deferred that capture until its use which by that time engine.delegate had been set. While we might be able to use @autoclosure somehow, the best solution is to just make runEngine and stopEngine functions.

  func runEngine() {
    print("Engine has been started")
    delegate?.engineDidStart()
  }

  func stopEngine() {
    print("Engine has been stoped")
    delegate?.engineDidStop()
  }
like image 56
Price Ringo Avatar answered Jun 17 '26 12:06

Price Ringo