方法和屬性(Methods and properties)
你也可以在enum中像這樣定義方法:
enum Wearable {
enum Weight: Int {
case Light = 1
}
enum Armor: Int {
case Light = 2
}
case Helmet(weight: Weight, armor: Armor)
func attributes() -> (weight: Int, armor: Int) {
switch self {
case .Helmet(let w, let a): return (weight: w.rawValue * 2, armor: w.rawValue * 4)
}
}
}
let woodenHelmetProps = Wearable.Helmet(weight: .Light, armor: .Light).attributes()
print (woodenHelmetProps)
// prints "(2, 4)"
枚舉中的方法為每一個(gè)enum case而“生”。所以倘若想要在特定情況執(zhí)行特定代碼的話,你需要分支處理或采用switch語句來明確正確的代碼路徑。
enum Device {
case iPad, iPhone, AppleTV, AppleWatch
func introduced() -> String {
switch self {
case AppleTV: return "\(self) was introduced 2006"
case iPhone: return "\(self) was introduced 2007"
case iPad: return "\(self) was introduced 2010"
case AppleWatch: return "\(self) was introduced 2014"
}
}
}
print (Device.iPhone.introduced())
// prints: "iPhone was introduced 2007"
屬性(Properties)
盡管增加一個(gè)存儲(chǔ)屬性到枚舉中不被允許,但你依然能夠創(chuàng)建計(jì)算屬性。當(dāng)然,計(jì)算屬性的內(nèi)容都是建立在枚舉值下或者枚舉關(guān)聯(lián)值得到的。
enum Device {
case iPad, iPhone
var year: Int {
switch self {
case iPhone: return 2007
case iPad: return 2010
}
}
}
靜態(tài)方法(Static Methods)
你也能夠?yàn)槊杜e創(chuàng)建一些靜態(tài)方法(static methods)。換言之通過一個(gè)非枚舉類型來創(chuàng)建一個(gè)枚舉。在這個(gè)示例中,我們需要考慮用戶有時(shí)將蘋果設(shè)備叫錯(cuò)的情況(比如AppleWatch叫成iWatch),需要返回一個(gè)合適的名稱。
enum Device {
case AppleWatch
static func fromSlang(term: String) -> Device? {
if term == "iWatch" {
return .AppleWatch
}
return nil
}
}
print (Device.fromSlang("iWatch"))
可變方法(Mutating Methods)
方法可以聲明為mutating。這樣就允許改變隱藏參數(shù)self的case值了
enum TriStateSwitch {
case Off, Low, High
mutating func next() {
switch self {
case Off:
self = Low
case Low:
self = High
case High:
self = Off
}
}
}
var ovenLight = TriStateSwitch.Low
ovenLight.next()
// ovenLight 現(xiàn)在等于.On
ovenLight.next()
// ovenLight 現(xiàn)在等于.Off