Hello everyone. Today I have a free hour so I've decided to write a little post about some basic and interesting Swift feature. And since today I had the need 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 there are properties that 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 and 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 very easy to use in Swift! Let's see an example:
The use case that I was facing today was a computed property that represents 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 selected pieces to the total every single time the property is being 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, I hope you enjoyed it. If you have any questions please leave a comment below. Good bye!