我只是想知道这两种定义变量的形式是否彼此不同。或者应该在某些特殊场景下使用。
var string1: String {
return "ok"
}
var string2: String = "ok"
最佳答案
第一种方法称为 computed property :
Classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
您使用的表单仅为 string1
提供了一个 getter,这使其成为只读属性。
第二种方法声明通常stored property :
A stored property is a constant or variable that is stored as part of an instance of a particular class or structure. Stored properties can be either variable stored properties (introduced by the var keyword) or constant stored properties (introduced by the let keyword).
在您的情况下,它是一个读写属性(使用 var
关键字声明)。
什么时候应该使用取决于具体情况。但有时只能引入计算属性(例如,如果您提供扩展)。
关于string - swift 中定义字符串变量的两种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717937/