Swift 的文档说,课程、 结构和 枚举都可以遵守协议,我可以达到它们都遵守的程度。但是我不能让 枚举表现得像 同学们和 结构那样:
protocol ExampleProtocol {
var simpleDescription: String { get set }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
enum SimpleEnum: ExampleProtocol {
case Base
var simpleDescription: String {
get {
return "A Simple Enum"
}
set {
newValue
}
}
mutating func adjust() {
self.simpleDescription += ", adjusted"
}
}
var c = SimpleEnum.Base
c.adjust()
let cDescription = c.simpleDescription
我还没有想出如何让 simpleDescription
作为调用 adjust()
的结果改变。我的示例显然不会这样做,因为 Getter有一个硬编码的值,但是我怎样才能在仍然符合 ExampleProtocol
的情况下为 simpleDescription
设置一个值呢?