Immutable Models — Swift

Kostiantyn Koval
Swift Programming
Published in
2 min readOct 21, 2014

--

I’ve just read Mikael Konradsson post “Keep-your-swift-models-clean”.
I like that. I really like that, especially start —

I’ve been a fan of Robert C. Martins (Uncle Bob) book Clean Code since I read a few years ago. If I had to name one book that every programmer should bring to that fictional lonely island, then it would be Clean Code.

But there is one thing that I would like add to that —
Try making your model immutable.

If we look at first example of the model, it’s really simple. A person with first and last name and constructor — the way to make a person. The firstname and lastname are declared as variables. The question is — why do we need to have mutable first and last name?

https://gist.github.com/Konrad77/36999217bf4055071d2a

Let’s make the model immutable. Change var to let. That’s it. We are done.

Maybe someone would argue and say that it should be possible to modify person object. If we add an age and want to change age. I like having as much immutable object as possible, so I want to demonstrate how I would made that. Also if you really need to have mutable models. That’s fine, make it mutable. But start with immutable first.

It’s easier to go from immutable to — mutable. And much more harder other way. I would be really happy if after reading this you would keep in mind 1 my advice.

Start with immutable models. Declaring new class — declare it with let properties.

The Best immutable Model

You can go further and make it even better immutable model. The best solution would be using Struct. Structs are immutable by default in Swift

The only thing you need to change is a class keyword to struct.
Also struct has a default initializer for all its properties, so we can remove a constructor. Less code is better ☺
Thanks to Mikael Konradsson for inspiring me to write that post.

Swift High Performance

If you enjoyed this article check out “Swift Hight Performance” book

--

--

Kostiantyn Koval
Swift Programming

Life Coach — Helping people to achieve their dreams, life fully, love passionate and live life of no regrets