final and lazy keywords in Swift

final
Mark methods,classes and variables as final to improve the performance if you know that the method won’t be overridden.

final func printMessage(message:String) {
  println("Log: "+message)
}

 

lazy
Mark your variables / properties with lazy to initialize them when you access the variable / property the first time.

class ViewController: UITableViewController {

    lazy var geoManager = GeoManager.sharedInstance
    var dataSource = WikiArticle[]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.geoManager.start()
    }
    .....
}

The geoManager will be initialized lazy. That means that the instance for the property will be created when we access the property the first time (in viewDidLoad).
“You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.”Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/de/jEUH0.l

But: Swift lazily initializes global constants (and variables) per default.

let theSharedInstance = Singleton()
class Singleton  {

    class var sharedInstance : Singleton {
        return theSharedInstance
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *