< When would you use self in a method? | What’s the point of static properties and methods in Swift? > |
Swift’s lazy properties let us delay the creation of a property until it’s actually used, which makes them like a computed property. However, unlike a computed property they store the result that gets calculated, so that subsequent accesses to the property don’t redo the work. This allows them to provide extra performance when they aren’t used (because their code is never run), and extra performance when they are used repeatedly (because their value is cached.)
However, that doesn’t mean we should make every property lazy, or indeed most properties – in practice, the majority of properties are just standard stored properties. There are a few reasons why you would prefer stored or computed properties over a lazy property, such as:
When trying to optimize code, it’s usually a better idea to wait until you actually have a problem you need to optimize rather than prematurely scattering things like lazy properties around.
For another perspective on lazy properties in Swift, check out this article from Keith Harrison: https://useyourloaf.com/blog/swift-lazy-property-initialization/
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.