I was trying to get the grasp of getters and setters in Swift. Here's some code that I wrote.
class SomeClass {
var var1: Int
var var2: Int{
get{
return 7 * var1
}
set(newValue){
newValue * var1
}
}
init(_ var1: Int){
self.var1 = var1
}
}
var obj = SomeClass(3)
var objComputedProp = obj.var2
print(objComputedProp) //this prints 21
objComputedProp = 14 //I want to change var2's value to 14 (give it a newValue),
//so that var2(which is objComputedProp) returns 14*var1 (which would be 42)
print(objComputedProp)//this prints 14
I understand that when we write var obj = SomeClass(3)
, var1
in the class becomes 3
and the getter returns 7 * var1
. But how do I access the setter? Setting objComputedProp
to 14
just assigns it 14.
I also tried changing var1
, but this just prints the same number twice:
var obj = SomeClass(3)
var objComputedProp = obj.var2
print(objComputedProp)
obj = SomeClass(5)
print(objComputedProp)