Day 7 : Structs, Properties, and Methods

An introduction to Struct

Jimmy Liu
Kuo’s Funhouse
Published in
6 min readOct 13, 2019

--

What is a Struct ?

A Struct is a model, which is a container for storing data and defining model behavior. It is very similar to a Class. The main difference between the two is that a Struct passes by Value whereas a Class passes by Reference.

So whenever you are passing a struct as a parameter, the function will hold a Copy of the struct. On the other hand, when a class is passed in as a parameter, the function will get hold of a Reference of its Memory Position.

I will discuss more on the differences between the two and how to choose between the two in another article. So stay toon.

How to create a Struct ?

All you need to do is to use the keyword struct before the name of your struct.

Inside, you can set properties and methods for this model. Let’s take a look at how to set up properties.

Setting Up Properties

Let’s begin by creating a struct called AccountInfo. Like any user account, it contains personal info, such as user’s name, phone number, password, sex and some info about the bank you opened your account at.

Properties inside a struct do not need to be initialized, instead, Swift will automatically generate a initiator :

Setting a Private Variable inside struct

However, it is not wise to leave password public, you don’t want anyone to mess around with the password now do you? So let’s make it a private property instead.

Once you set password to private, you will get an error on the AccountInfo initializer :

So what can you do ?

No need to worry, simply create a initializer in the struct yourself :

Now you can initiate password when creating an AccountInfo.

Since password is now private, we need to figure out how to modify and confirm password when entered. This require the help from other methods.

Creating Methods

When creating a method, if the method involved in altering values of the struct, we need to put mutating before the function.

In this case, we need to modify the password, so we created a function called authorizingSetPassword. This function needs to take in an access code to make sure the user is authorized to change the password, and a new password.

When setting a new password, we need to check if the password is valid as well, so let’s refractor the code into :

By setting setPassword to private , we make sure that no one from the outside can change password without access code.

So do we need to write this amount of code for every variable in a struct ?

No, this is needed only because we set password to private. Let’s take userPhoneNumber as an example.

userPhoneNumber is an internal variable, and outsider can simply edit it by calling :

Note : if I make account a let or a constant, then all the internal properties will become a constant as well.

As you can see, userPhoneNumber does not have any protection against incorrect format of phone numbers. So we need to create a function called validPhoneNumber that takes the new phone number as an input and output a boolean value.

However, here comes the question. Since validPhoneNumber should not be called directly, it is set to private. So where should we use this function ?

Don’t worry, property observers come to the rescue.

Property Observers

Here is a great article on property observers by Onyekachi Ezeoke.

In Swift, when a property is being accessed or modified, it will trigger the property’s getter and setter. When a setter is override, Xcode will ask for a getter as well.

However, we are not interested in getter and setter. Instead, we are more interested in its property observers, willSet and didSet.

As their names implied:

  • willSet is triggered before modifying the property. You get to access a the new value by calling newValue.
  • didSet is triggered after the modification is completed. You get to access the old value by calling oldValue.

Note : Both property observers will not get triggered when property is being initialized.

My first instinct is to call validPhoneNumber method inside willSet, since this is the first location where you check the validation of the phone number.

Unfortunately, this is impossible. During willSet, you won’t be able to change the newValue, because it is a let or constant value. Also, even if you return from the willSet, didSet will still be called.

Since willSet is not suitable for our need, let’s try didSet.

Even though we set the value of userPhoneNumber inside didSet, but apparently, this does not trigger both willSet and didSet.

Now you know how to create a struct with properties and methods, both dynamic and static, let’s take a look at access control, such as private and internal, what do they do.

Access Control

In Swift, access control is divided into 5 categories, from the least restrictive to the most restrictive are :

  • Open Access and Public Access : They enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. They are typically used when specifying the public interface to a framework.
  • Internal Access : It enables entities to be used within any source file from their defining module. It is typically used when defining an app’s or a framework’s internal structure. This is the default access control level.
  • File-Private Access : It can only be used in its own defining source file. Use it to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
  • Private Access : It can only be used inside the enclosing declaration ({}), and to extensions of that declaration that are in the same file. Use it to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

You can find lots of example when examining source code from Third-Party library.

Summary

A Struct is a container that stores properties and defines methods. Unlike a class, a struct is passed by value instead of reference. If a method wish to edit properties within a struct, it will need to be stated by using the keyword mutating before func .

When a struct is declared as let value, then all its properties cannot be edited, even if the method has mutating before func .

Any value and method can have it’s own access control level depending on the needs. By default, internal is used. If you wish to hide sensitive info from outsider then use private instead.

In order to edit or fetch values within a struct, you can either define (mutating) functions or you can use property observers (willSet didSet). A property observer can only applied to variables that has been initialized. If no initialization was performed in initialization of the struct, then you can only use get set to get and set the value of the property.

Finally, I hope now you have understand more about struct and how to use it. Next time, I will talk about Class, so stay toon.

--

--

Jimmy Liu
Kuo’s Funhouse

App Developer who enjoy learning from the ground up.