Home > Enterprise >  Different between assign value / operating add, times, minus to an object in Swift?
Different between assign value / operating add, times, minus to an object in Swift?

Time:08-19

I'm trying out private(set) in playground.

Say, a person named Slippin Jimmy, his age property shouldn't able to operate outside person class since age variable have a private(set) prefix.

I can't direct assign a value to age property, But I can still operate age like plus 1, minus1, times it, I think this is because there's no new variable to store data, no-matter how I operate age variable, it still hold same value from person class, right?

So what's different between 1, - 1, * 1 and = 1 in this scenario?

class person {
   var name = "Slippin Jimmy"
   private(set) var age = 18
   func getOlder() {
      age = age   1
       print(age)
   }
}
var saul = person()
print("saul's age is \(saul.age)")//saul's age is 18

saul.getOlder()//19

saul.age   1 //20
saul.age - 1 //18
saul.age * 3 //57

//saul.age = 22//cannot assign to property: 'age' setter is inaccessible

print("saul's age is \(saul.age)")//saul's age is 19

CodePudding user response:

Person.age has a private setter. That means you cannot set the value of age from outside of the class. You can still talk about it (access its value) though, because its getter is not private, and that is exactly what the code in question is doing - mention its value when describing some other number. All of these are expressions that do not set the value of age:

saul.age   1
saul.age - 1
saul.age * 3

From top to bottom, they mean:

  • the value that is one more than saul.age
  • the value that is one less than saul.age
  • the value that is three times more than saul.age

You're just talking about some numbers! :) On the other hand, if you have said:

saul.age = 20

Then it means "change saul.age to 20", and that is not allowed because age has a private setter.

Side note: in normal Swift files, expressions like saul.age 1 are not allowed at the top level. The fact that this compiles for you suggests that you are probably in a Swift Playground.

  • Related