Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Learning Swift
  • Table Of Contents Toc
  • Feedback & Rating feedback
Learning Swift

Learning Swift

By : Andrew J Wagner
4.8 (5)
close
close
Learning Swift

Learning Swift

4.8 (5)
By: Andrew J Wagner

Overview of this book

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.
Table of Contents (13 chapters)
close
close
12
Index

Lazy properties


One feature we have not discussed yet is the concept of lazy properties. Marking a property as lazy allows Swift to wait to initialize it until the first time it is accessed. This can be useful in at least a few important ways.

Avoiding unnecessary memory usage

The most obvious way to use lazy properties is to avoid unnecessary memory usage. Let's look at a very simple example first:

struct MyType {
    lazy var largeString = "Some String"
}
let instance = MyType()

Even though we created a new instance of MyType, largeString is not set until we try to access it. This is great if we have a large variable that may not be needed for every instance. Until it is accessed, it does not take up any memory.

Avoiding unnecessary processing

We can also take this idea of a lazy property even further using a closure to calculate the value:

class Directory {
    lazy var subFolders: [Directory] = {
        var loaded = [Directory]()
        // Load subfolders into 'loaded'
        return loaded...

Unlock full access

Continue reading for free

A Packt free trial gives you instant online access to our library of over 7000 practical eBooks and videos, constantly updated with the latest in tech
bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY