From the course: Practical Design Patterns in Swift

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Delayed initialization

Delayed initialization - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Delayed initialization

- [Instructor] We can use Swift lazy properties to implement the virtual proxy pattern. Our aim is to delay the creation of expensive objects until they are actually used. In this example, we'll create a class called RandomIntWithID. So let's create the class. It has a property called value of type Int. I'm going to initialize it using closure. The closure prints a console log and returns a random integer. We print value initialize so that we can keep track of its initialization. And I return a random integer. The uid property is a lazy property of type string. Lazy var uid of type string. And I use a closure to initialize it. Again we print to the console that it's been initialized, and I return a unique identifier's string representation. For the uid type, I need to import foundation framework. Now let's create a random int with ID instance and run the playground. Let n equals RandomIntWithID. The uid's closure should only be executed when we access it. The log shows that the value…

Contents