Properties in Swift

The values you use every day

Properties are the association of a value with a class, struct or enum. But it can be quite confusing to the beginner that we can have stored or computed properties, and that they can even be lazy.

The idea of this particular tutorial is to make these terms slightly easier to understand, and provide a nice reference.

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Understand the difference between a class and a struct (tutorial HERE)

Terminology

Computed Property: A value that is computed (rather than set)

Property: An association of a value with a class, structure or enumeration

Stored Property: A constant or variable that is stored as part of a class or a struct

Value: A possible result of an implementation

Properties

A rectangle can be represented by the following struct:

We can see that height and width are representing in this struct as variable stored propertiesand of course constants can be stored as aletconstant (Need a reminder about let and var? I’ve got you covered HERE) although this is not shown in the struct above.

Computed Properties

This example is a square (this is pretty much the same as the rectangle above, but still…).

We can calculate the area of the square by multiplying width * height as shown in the Square below:

In this instance I’ve provided agetter declaration and no setter declaration (detailed explanation)

Lazy Stored Properties

This is a stored varvariable that is only calculated when it is used.

If you try to create a lazy var outside a struct or a class you’ll be met with an ordinary-looking error message in the playground

Image for post
Image for post

well, that’s us told.

So what do we do?

Imagine you want to set up a person like this:

Now we can think (for no real purpose) we want to be able to calculate the person’s age times by 2.

The thing is, as age can change (every year) we need to calculate the double age only when it is requested. So we use a lazy var for this.

The variable itself must be a var since doubleAge can change.

Mutating getters (like the example above) necessitate that the variable (in this case the person) needs to also be a variable.

The lazy property ends in () because it is treated as a function rather than a simple property!

Conclusion…

Properties are vital in any programming language. As you can see from the list above they can actually be quite in-depth. However this is something which is really important to get a grip on, and develop your own Apps using this knowledge.

Want to get in contact? Try the link here:

https://twitter.com/stevenpcurtis

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store