Swift Quick Hints. Setters & Getters.

Just in case you didn’t know — this is a setter on the image below.

Real setter

Just kidding. So how to assign a value to swift class or struct variables. You can do it like this.

It’s simple, yeah?

What if you want to change title in immutable struct to some other value? You can change it from let to var. Nothing new for us. But this code smells.

So what?

What if you want to do something with the title before storing it in your already mutable struct? And you don’t want smelling code. Of course you do it like this.

So far so good!

Now let’s get a title. Title is a private now so we should add a new getter function.

Looks fine? No!

Now it looks like old school Java boilerplate code from 90’s. Let’s make something with that. We can make it like this and get rid of initializer and getter. Actually don’t do this because your variable becomes public.

Better now, but variable is public again

Watch this. You can say that variable has private setter but public getter just in a one line of code.

Public getter — Private setter

We have more syntax sugar inside Swift. Example belowe is just an illustration. Don’t try to find a meaning of life here. newTitle is a computed property, it acts only like a getter and setter for a title. Title is also accessible from outside. In a computed property you can access a new value in a setter via newValue variable

Yet another way to change something related to New Value event is to use willSet and didSet triggers. Take a look at the code below. App assigns value to a variable title in a didSet trigger and it doesn’t fall into infinite loop here! Amazing! Also you can use oldValue in didSet to get, well, and old value.

No infinte loop here!
Log

DONE

Thanks for reading and you’re welcome to hire us at Pharos Production Inc.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.