Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在swift中,括号中的set是什么意思?_Swift_Class_Variables_Accessor - Fatal编程技术网

在swift中,括号中的set是什么意思?

在swift中,括号中的set是什么意思?,swift,class,variables,accessor,Swift,Class,Variables,Accessor,getter和setter是可以理解的,但是在阅读了一篇文本教程之后,我很难理解在声明变量时括号中的“set”是什么意思 private (set) var price:Double{ get{return priceBackingValue} set{priceBackingValue=max(1,newValue)} } 在变量范围和命名约定中添加“set”的目的是什么?这意味着用于设置变量价格的访问修饰符是私有的,而作为变量仍然可以访问。就好像它是公开的一样 class

getter和setter是可以理解的,但是在阅读了一篇文本教程之后,我很难理解在声明变量时括号中的“set”是什么意思

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

在变量范围和命名约定中添加“set”的目的是什么?

这意味着用于设置变量价格的访问修饰符是私有的,而作为变量仍然可以访问。就好像它是公开的一样

class Doge {
  private(set) let name = ""
  func someMethod(newName: String) {
    name = newName //This is okay because are setting the name from within the file
  }
}
在另一个文件中注意:private表示文件的私有,而不是类的私有!:

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

编辑:更准确地说,私有如何应用于文件,而不是实际的类-如@sschare所述,它基本上表明可变价格仅可由定义它的类设置,即它是私有设置器。如果您希望变量可由其他类读取,但只能由定义它的类设置,则这非常方便

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!
而在本例中,其他类根本无法访问该变量,既不可设置也不可获取

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 

正如sschale在评论中指出的那样,显然,将类放入相同的文件将向同一文件中的其他类公开类的私有成员/属性,因此在将多个类放入文件时要考虑到这一点

所以你的意思是,它被声明为私有,所以其他类无法访问它…但是通过添加“set”,那么该属性可以访问其他类只能设置该属性的位置?@LaurenceWingo本质上是的,因此,将其视为仅私有意味着setter和getter都是私有的,但privateset意味着私有访问修饰符只应用于该集。明白了!!只是想确定一下。在您上面的代码中,如果我们将“set”更改为“get”,那么myDoge.name=foo将是允许的,并且工作正常吗?@LaurenceWingo实际上没有这样的privateget,因为setter的访问修饰符必须小于或等于getter。如果我们可以在其类之外更改变量,但不能访问它,那么这将不会有很大帮助。您可以为变量的get应用访问修饰符,也可以为set应用修饰符,如下所示:internal privateset var…@LaurenceWingo如果这个答案有用并且回答了您的问题,你能把它标记为选中的答案吗:如果一个类的私有组件在同一个.swift文件中,你实际上可以访问它们。这是非常正确的,我还要补充一点。我的主要目的是在一个真实的用例中说明这一点,其中类驻留在不同的文件中,但同样,您的观点是完全正确的。