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!
Top comments (5)
CRAZY BRO! 💪🏼
VueJS. That was one of the features that I liked the most.
Thanks for commenting! Computed properties are useful especially in SPA and MVVM frameworks, I'm pretty sure you've taken advantage of them. PD: I'm interested in learning VueJS, any valuable resource you'd recommend?
Sure bro! I Think the best resource is the documentation and a great course from Udemy Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex) by Maximilian Schwarzmüller (one of the best udemy's instructor)
Cool, thank you.
I recently learned about „didSet“ and „willSet“. That would make a good candidate for a follow up article.