swift - “var simpleDescription: String {get}”中的“get”有什么作用?
问题描述
我在 Apple Swift Tour页面中看到了这个示例。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
我们可以创建一个符合这个协议的类
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
我们可以轻松获取和设置属性 simpleDescription 的值。
let a = SimpleClass()
a.simpleDescription = "new description"
print(a.simpleDescription)
get
在做什么var simpleDescription: String { get }
?我们可以删除它吗?
解决方案
协议的简要背景
实现协议中定义的所有代码的任何类、结构或枚举都被称为符合该协议。协议可以要求任何符合的类型来提供属性(具有特定名称和类型的实例属性或类型属性)。1协议中定义的每个属性(例如var simpleDescription: String
在下面的示例中)还必须在类型声明之后(例如String
下面示例中的类型)指定它是 gettable{ get }
还是 gettable 和 settable { get set }
。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
Gettable { get } 与 Gettable 和 Settable 属性 { get set }
通常,可获取和可设置的属性{ get set }
必须是可设置的,这意味着可以编辑/更改属性的值。因此,可获取和可设置的属性不能是常量存储属性(使用let
关键字初始化的属性)或只读计算属性。如果协议只要求属性是可获取{ get }
的,则任何类型的属性都可以满足该要求,并且如果这对您自己的代码有用,则该属性也可设置是有效的。1
可获取属性与可获取和可设置属性的示例:
// Gettable (var property)
protocol FishSpecies {
var speciesName: String { get }
}
struct Fish: FishSpecies {
var height: Int
var weight: Int
var speciesName: String
}
var tuna = FishSpecies(speciesName: “Yellowfin”)
print(tuna.speciesName) // returns “Yellowfin”
tuna.speciesName = “Thunnus albacares”
print(tuna.speciesName) // returns “Thunnus albacares”
// Gettable (let 'constant' property)
protocol FishSpecies {
var speciesName: String { get }
}
struct Fish: FishSpecies {
var height: Int
var weight: Int
let speciesName: String
}
let tuna = FishSpecies(fishName: “Yellowfin”)
print(tuna.speciesName) // returns “Yellowfin”
// Gettable and Settable (Constant Property)
protocol FullyNamed {
var fullName: String { get set }
}
struct Golfer: FullyNamed {
let fullName: String
}
let baller = Golfer(fullName: “Collin Morikawa”)
// -> Error message: Type ‘Golfer’ does not conform to protocol ‘FullyNamed’
// Gettable and Settable properties cannot be constant stored properties
// Gettable and Settable (Computed Property)
protocol FullyNamed {
var fullName: String { get }
}
struct Golfer: FullyNamed {
fileprivate var name: String
var fullName: String {
get {
return name
}
set {
name = newValue
}
}
}
var bigCat = Golfer(name: "Woods")
print(bigCat.fullName) // returns "Woods"
bigCat.fullName = "Tiger Woods"
print(bigCat.fullName) // returns "Tiger Woods"
参考资料/延伸阅读
推荐阅读
- kubernetes - Kubernetes Dashboard CrashLoopBackOff,出现错误“connect: no route to host”,我该如何解决?
- marklogic - MarkLogic 部署错误'/config/query not found for write'
- firebase - Firebase 手机身份验证颤动崩溃
- date - 在 Julia 中:星期几默认为星期一=1,如何设置星期日=1
- python - 根据该字典中键的特定值过滤字典列表
- java - 当以太网电缆从系统中拔出时如何注销应用程序?
- c# - 使用 Xamarin 表单打开 PDF
- angularjs - 更新克隆列表时如何阻止原始列表更新
- mongodb - 单个 mongo 查询中的多个计数查询
- mysql - 在 Windows 中安装 gzip 并使用 gunzip 命令