enum PaymentType {
case cheque(issuer:String)
case creditCard(number:String)
var description: String {
switch self {
case let .cheque(issuer): return "Cheque issued by \(issuer)"
case let .creditCard(number): return "Credit card number \(number)"
}
}
}
ทำให้เราสั่ง .description ได้ แบบนี้
PaymentType.cheque(issuer: "SCB").description
นอกจากนี้ Enum ยังสามารถมีฟังก์ชันได้ด้วย เช่น
enum PaymentType {
case cheque(issuer:String)
case creditCard(number:String)
var description: String {
switch self {
case let .cheque(issuer): return "Cheque issued by \(issuer)"
case let .creditCard(number): return "Credit card number \(number)"
}
}
func description(with name: String) -> String {
return String(format: "Name: %@, Type: %@", name, self.description)
}
}
PaymentType.cheque(issuer: "SCB").description(with: "Supakit")
enum TapSwitch {
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
}
}
}
var state = TapSwitch.on
state.toggle()
state.description