Tài liệu Swift nói rằng các lớp , cấu trúc và enum đều có thể tuân theo các giao thức và tôi có thể đạt được điểm mà tất cả chúng đều tuân theo. Nhưng tôi không thể khiến enum hoạt động giống như các ví dụ về class và struct :
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
Tôi chưa tìm ra cách nhận simpleDescriptionthay đổi do gọi điện adjust(). Ví dụ của tôi rõ ràng sẽ không làm điều đó bởi vì getter có một giá trị được mã hóa cứng, nhưng làm cách nào để tôi có thể đặt một giá trị simpleDescriptiontrong khi vẫn tuân thủ ExampleProtocol?