Steve Steve - 1 month ago 9
Swift Question

Need clarification regarding computed properties

I am currently learning Swift from a Java/Node.js background. After reading about computed properties, I was wondering as to the difference between the following two uses:

private var _privateVariable: String = "test"

var testVariable {
return _privateVariable
}

var testVariable {
get{
return _privateVariable
}
}


Essentially, what is the difference in usage between using a getter with the
get
keyword and simply returning another variable within the original variable declaration?

Answer Source

There is no difference at all. This is a mere shortcut.

When you write

var testVariable {
   get{
      return _privateVariable
   }
}

you can add setter at any point:

var testVariable {
   set{
      _privateVariable = newValue
   }
   get{
      return _privateVariable
   }
}

While the other case is useful to shorten your code when you don't need a setter.