Computed property and Stored property in Swift
--
Computed property
A computed variable behaves syntactically like a variable but does not actually require storage. computed property just recalculate the block of code whenever it’s called and returns the value.
In short, “A computed property is one that runs some code in order to calculate the value.”
Stored property
The simplest form of a variable declaration provides only a type. Stored variables must be initialized before use. As such, an initial value can be provided at the declaration site.
In short, “A stored property is one that saves a value for use later.”
I have created one class
class MyClass { init() {
print(“MyClass init”)
}}
Computed property Example
var myClassObj: MyClass { return MyClass()}print(myClassObj) //“MyClass init”print(myClassObj) //“MyClass init”
😱😱😱😱
Yes, MyClass instance is created two times here. so whenever you call Computed property it will recalculate every time.
Stored property Example
var myClassObj: MyClass = MyClass() //“MyClass init”print(myClassObj) print(myClassObj)
🤩🤩🤩🤩
So here MyClass instance is created once. so whenever you call Stored property it will provide you the same instance.
So both have there different advantages/disadvantages
For more visit: https://ioslifee.blogspot.com
Thanks for reading, Happy Coding 💻