Created
July 6, 2020 07:03
-
-
Save stevencurtis/9e308e798dac9ca99cbb873b0e27fd7c to your computer and use it in GitHub Desktop.
lazyexample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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