Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 4: Properties & Methods

31. Lazy Properties

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 30. Computed Properties Next episode: 32. Challenge: Properties

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 31. Lazy Properties

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Transcript: 31. Lazy Properties

We’re back with our Wizard struct, and there’s one last thing I’d like to show you, that you can do with instance variables. Let’s say we want to add another stored property, like magicalCreature, and just for a moment, assign it an empty String

63 var magicalCreature = ""

Now, add the keyword lazy before var magicalCreature. That’s the last concept I want to show you regarding stored properties.

63 lazy var magicalCreature = ""

Without the lazy keyword, this assignment would happen at initialization. But now, it won’t happen until the first time you need it.

That doesn’t really make sense for an empty string, but it does, if calculating the variable’s value is a costly operation. To emulate one of those, there’s a function in the Sources folder which summons a magical creature.

You can check it out if you want if you want, but you don’t need to. Just imagine that it represents an operation that might take a long time or require a lot of memory.

Calling summonMagicalCreature requires the name of a summoner. And because a lazy variable won’t be assigned until after initialization, we can use the instance property fullName.

63   lazy var magicalCreature = summonMagicalCreature(summoner: fullName)

Now, that will work, but try to create another Wizard and you’ll see something interesting.

var wizard = Wizard(firstName: "Gandalf", lastName: "Greyjoy")
😺Wizard(firstName: <#T##String#>, lastName: <#T##String#>, magicalCreature: <#T##String?#>)🛑

So far, we’ve been relying on what’s called the “memberwise initializer”. Wizard has three stored properties, now, and when you try to initialize a Wizard instance, you get this initializer asking you to provide values to all of them.

The memberwise initializer Swift generates will still think it needs a magicalCreature, even though it doesn’t really need that from you. Also note that the magicalCreature is treated as an optional.

So, when that argument is left out of the initializer, it’s just assumed that Gandalf Greyjoy’s magical creature is nil.

If you want an initializer that actually does what the old one did: just assign a first and last name, without any extra deleting from you, you’ll have to write your own!

var wizard = Wizard(firstName: "Gandalf", lastName: "Greyjoy")
❌Wizard(firstName: <#T##String#>, lastName: <#T##String#>, magicalCreature: <#T##String?#>)❌

You wrote an initializer for a Class in the Swift fundamentals course. Simple ones work much the same, for structures. They look a lot like methods that don’t have a return value. Except you always use the keyword init instead of a method name.

65 init(firstName: String, lastName: String) {
    
  }

That’s the signature you see below; now you just need to assign firstName to self.firstName, and lastName to self.lastName

66 self.firstName = firstName
self.lastName = lastName

Now, at the end of the end of the playground, let’s print out our wizard’s magical creature!

print(wizard.magicalCreature)

So, notice at the bottom, that the name of the summoner is “Severus Wenderlich”, not any of the previous names our wizard had. Now, let’s change the name of the wizard to “Qui-Gon Crayskull”, and print out his magical creature.

wizard.fullName = "Qui-Gon Crayskull"
print(wizard.magicalCreature)

We can see in the printout, that Severus is being set to Qui-Gon, but the magical creature is still listed as being summoned by Severus. Well, that’s true!

A lazy stored property is different than a computed property. With the code we’ve written, the name of wizard at the time they summon the magicalCreature is stored with the creature, for further use.

Now, if that’s not what you wanted, you could change the summonMagicalCreature code, to only return the creature itself, and not the summoner. The point was to show you the timing difference between lazy variables and computed properties.

You can think of lazy variables as something in being in-between constants that get set at initialization, and computed properties, which get evaluated every time you call them.

If you have something that could be a constant, but it’s expensive to calculate, and you think it might not get used for every instance, then a lazy variable might be the right option.