Swift computed properties in a nutshell
Eleazar Estrella

Eleazar Estrella @eleazar0425

About: Passionate Mobile Developer with strong experience in Android/Java and iOS/Swift

Joined:
Feb 13, 2018

Swift computed properties in a nutshell

Publish Date: Sep 4 '18
39 5

Hello everyone. Today I have a free hour, so I've decided to write a little post about some essential and exciting Swift features. And since today, I needed to use computed properties in my job; I want to share that knowledge with whoever is starting in the world of programming as well as in iOS and Swift. With nothing more to add, let's begin.

What are computed properties?

Sometimes in our classes, some properties are not so simple as to be only quantities or values ​​represented in a variable (such as the value of a string, integer, etc.). Some times in execution time, we need some business logic behind some properties for its correct operation. Instead of encapsulating that logic in functions, we can also do it in the so-called computed properties. Every time we access this kind of property, its value is recalculated, this brings many advantages, and it's also straightforward to use in Swift! Let's see an example:

The use case that I was facing today was a computed property representing the total value of the selected pieces within a group of data. As the selected pieces can change on the fly, it's necessary to do the calculation again by iterating and adding the price of the chosen pieces to the total every single time the property is accessed. The way to do this in Swift is to open brackets right after declaring the property, and inside the getter, we should write the logic necessary for it to work:

Each time the "total" property is accessed, it iterates recalculating the value based on the selected pieces. As you can see, the advantages are several, starting with having a more concise code and always having the property value updated. You can also create "writable" computed properties using the keyword "set," do you want to try it out?

This has been my mini post for today, and I hope you enjoyed it. If you have any questions, please leave a comment below. Goodbye!

Comments 5 total

  • Marluan Espirituanto
    Marluan EspirituantoSep 5, 2018

    CRAZY BRO! 💪🏼

    In the JavaScript world, computed properties are very usefull too, for example in VueJS. That was one of the features that I liked the most.

  • Ikem Krueger
    Ikem KruegerSep 23, 2018

    I recently learned about „didSet“ and „willSet“. That would make a good candidate for a follow up article.

Add comment