การประกาศว่า conform protocol ใช้ : หลังชื่อของ Struct, Enum หรือ Class แล้วตามด้วย ชื่อของ protocol ที่เราต้องการ conform ซึ่งเราอาจ conform ได้มากกว่าหนึ่งอัน
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
enum TapSwitch: ItemDiscribable, Togglable {
case on
case off
var description: String {
switch self {
case .on: return "current is on"
case .off: return "current is off"
}
}
mutating func toggle() {
switch self {
case .on:
self = .off
case .off:
self = .on
}
}
}
let state = TapSwitch.on
print(state)
class Item: ItemDiscribable {
var name: String
var isDone: Bool
var description: String {
return name
}
init(name: String, isDone: Bool) {
self.name = name
self.isDone = isDone
}
}
let items: [ItemDiscribable] = [Item(name: "Test", isDone: false), TapSwitch.off]
for item in items {
print(item)
}
if item is Item {
print("item is Item")
}
if let item = item as? Item {
print(item.isDone)
}