Skip to content

Instantly share code, notes, and snippets.

@stevencurtis
Created July 6, 2020 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevencurtis/9e308e798dac9ca99cbb873b0e27fd7c to your computer and use it in GitHub Desktop.
Save stevencurtis/9e308e798dac9ca99cbb873b0e27fd7c to your computer and use it in GitHub Desktop.
lazyexample
// Lazy provides eferred property initialization
struct People {
lazy var names = ["Saanvi"]
}
// _ prefix is the Objective-C way to indicate a backing store
// _names
struct People {
private var _names: [String]?
var names: [String] {
mutating get {
// this returns the backing store, iff populated
if let initNames = _names { return initNames }
// populate the backing store, only if it has not previously
// been populated
let initialValue = ["Saanvi"]
_names = initialValue
return initialValue
}
set {
// set initialises the backing store
_names = newValue
}
}
}
var people = People()
print (people.names)
print (people.names)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment