先决条件:
进入你的操场,在下面写下 sn-p:
var height: Int {
get {
return 5
}
}
或类似:
var height: Int {
return 5
}
尝试打印height的值,显然有效。到目前为止一切顺利
print(height) // prints 5
但是,如果您尝试将其设置为新值,则会收到错误消息:
height = 8 // ERROR
错误:无法赋值:'height' 是一个 get-only 属性
答案:
根据马丁的回答,我先写了:
set(newValue) {
height = newValue
}
这给我的记忆带来了很多负担,并导致我提出this 的问题。请看一下。因此,我正在考虑要写什么,我有点明白,如果你不想做任何特别的事情,你不应该使用计算属性,而应该只使用普通的存储属性.
于是我写了一个类似的代码
protocol Human {
var height: Float {get set}
}
struct Boy: Human {
// inch
var USheight : Float
// cm
var height: Float {
get {
return 2.54 * USheight
}
set(newValue) {
USheight = newValue/2.54
}
}
}
// 5 ft person
var person = Boy(USheight: 60)
// interestingly the initializer is 'only' based on stored properties because they
// initialize computed properties.
// equals to 152cm person
print(person.height) // 152.4
专业提示:何时应将属性设为只读?
通常,如果您将属性设为只读,即{ get },这是因为这些属性是计算的,您不希望对象控制它。
例如,您有一个 JSON 对象。它有多个大对象,例如:
JSONData
- userInfo (name, address, age)
- devices (iPads, iPhones, Mac books)
- credentials (basic iCloud, pro iCloud, celebrity)
通过将角色设置为只读,您只允许服务器告诉代码库用户的角色。
protocol Credentials {
var role: String { get }
init(person: Person)
}
class Person {
var userInfo: String
var devices: [String]
var creds: Credentials {
Credentials(person: self)
}
init(userInfo: userInfo, devices: [String]) {
self.userInfo = userInfo
self.devices = devices
}
}