The Lazy Variables: What and Why in Swift
lazy var innit (not init)
3 min readMay 1, 2020
This article covers lazy variables, why you might use them and how they are used in Swift.
Difficulty: Beginner | Easy | Normal | Challenging
Prerequisites:
- Be able to code Swift using Playgrounds
- Some knowledge of closures would be useful
Terminology
closure: A self-contained block of functionality that can be passed around
lazy variables: A technique in that a property is only created when it is needed
Motivation
I recently completed a rather fantastic date manager in Swift, that creates the dateFormatter as a lazy var.
private lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
return dateFormatter
}()
The way this closure works is interesting, and demands more attention than can be given in a couple of sentences.
So let us press on!
The step-by-step
Properties can be rather easily set up, for example here an optional name
var name: String?