Apple Apps Club
Lesson - 1

Struct, Computed Properties, Stored Properties, Omissions of the return Keyword

Struct represents a structure. This structure is made up of properties and functions.
Stacks Image 28
Notice that you can omit the return keyword if you use only a single line

Now you can see that the fullName is nothing but the combination of firstName and lastName. So it can be computed from those two properties. So instead of passing the fullName ourselves while making the struct, let's make it a computed property.
Stacks Image 37
Now let's put a print statement inside our computed property fullName and see how many times it is printed when we run our code.

You can see it prints it twice that means it's computing the fullName every time we call it. Here we called it from out two functions.
Stacks Image 46
Let's make our fullName property a stored property that gets computed only once and it becomes stored and need not be computed again.

Notice that the program gives a compilation error.
Stacks Image 53
To resolve the compilation error, put lazy in front of var fullName

What is the compilation error? And why lazy resolves it?

A structure is made of all it's properties and when it is made, all of it's properties are also made (initialised). Here fullName can only be computed when firstName and lastName are available. But all 3 properties are made together. So you can not access firstName and lastName inside fullName.

lazy keyword tells swift that this property is lazy. So don't initialise it when structure is made. Do it only when this property is called from somewhere. This tells compiler that it need not worry about firstName and lastName not being available.
Stacks Image 60
To resolve the next compilation error, put mutating in front of both functions and make the 'let myself =…' to 'var myself =…'

What is the compilation error? And why mutating resolves it?

Structures are generally rigid, meaning most often we don't require them to change. But sometimes we do, like in this example, our functions are calling to property fullName that is lazy. That means after we call any of those functions our struct will have a new stored property called fullName, that is essentially changing the structure itself. That is why mutating keyword is required in front of those functions.

As you can see the structure will be changed after calling any of those functions, we need to declare the structure as variable and not constant. Thus we replace let with var.

Notice that now it prints 'computing full name' only once.
Stacks Image 67
You are done 🎉
Stacks Image 78