user5369493
user5369493

Reputation:

In swift, what does set in parentheses mean?

Getters and setters are understandable however after following a tutorial from a text, I'm having trouble understanding what the word 'set' in parentheses means when declaring the variable?

 private (set) var price:Double{
    get{return priceBackingValue}
    set{priceBackingValue=max(1,newValue)}
}

What is the purpose of adding '(set)' in the variable scope and naming convention?

Upvotes: 2

Views: 920

Answers (2)

Blake Lockley
Blake Lockley

Reputation: 2961

This means that the access modifier for setting the variable price is private, where as the variable can still be accessed (aka. get) as if it was public.

class Doge {
  private(set) let name = ""
  func someMethod(newName: String) {
    name = newName //This is okay because are setting the name from within the file
  }
}

In a different file (note: private means private to the file not class!):

let myDoge = Doge()
print(myDoge.name) //This is okay as we can still access the variable outside of the file
myDoge.name = "foo" //This is NOT okay as we can't set the variable from outside the file

EDIT: more accurate to mention how private applies to the file not actually the class - as mentioned by @sschale

Upvotes: 2

the_critic
the_critic

Reputation: 12820

It basically indicates that the variable price is only settable by the class that defines it, i.e. it is a private setter. This is convenient in cases where you want the variable to be readable by other classes, but only settable by the class that defined it.

class A {

  private (set) var foo = "foo" // variable can be read by other classes in the same scope, but NOT written to(!)

}

let a = A()
a.foo // fine! You can only read this one though!

whereas in this example, the variable is not accessible by other classes at all (neither settable nor gettable)

class B {

  private var bar = "bar" // other classes have no access to this variable

}

let b = B()
b.bar // you cannot read/write this variable 

As sschale points out in the comments, obviously putting classes into the same files will expose the private members/properties of a class to the others within the same file, so take that into account iff you are putting more than one class into a file.

Upvotes: 2

Related Questions