今天用到的Markdown語(yǔ)法:
Ordered Lists
Ordered lists are created using "1." + Space:
swift中枚舉類(lèi)型是一等類(lèi)型遏弱,具有很多傳統(tǒng)上只能被類(lèi)所支持的特性:
- 計(jì)算型屬性,用于提供枚舉值的附加信息
- 實(shí)例方法布讹,用于提供和枚舉值相關(guān)聯(lián)的功能
- 定義構(gòu)造函數(shù)瘾英,來(lái)提供初始值
- 遵守協(xié)議
我的理解:枚舉值就可以當(dāng)作類(lèi)忌堂。
定義了一個(gè)枚舉類(lèi)型,用case來(lái)定義一個(gè)枚舉成員值
enum CompassPoint {
case North
case South
case East
case West
}
當(dāng)directionToHead被賦值的時(shí)候拴曲,他的類(lèi)型就被推斷出來(lái)争舞,是枚舉類(lèi)型,下面使用的時(shí)候就可以用.South直接賦值
var directionToHead = CompassPoint.West
directionToHead = .South
用switch判斷枚舉值的時(shí)候澈灼,switch必須窮舉所有的情況竞川,不然編譯會(huì)報(bào)錯(cuò)
switch directionToHead {
case .North:
print("Lots of planets have a north")
case .South:
print("Watch out for penguins")
case .East:
print("Where the sun rises")
case .West:
print("Where the skies are blue")
}
我們列舉枚舉值的時(shí)候,可以使用如下叁熔,將所有的選項(xiàng)寫(xiě)在一行中
enum Planet{
case Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune
}
let somePlanet = Planet.Mars
switch somePlanet{
//當(dāng)我們不需要列出所有選項(xiàng)的時(shí)候委乌,我們可以使用default選項(xiàng)
case .Earth:
print("Mostly harmless")
default:
print("hahah,woxihuanni!")
}
關(guān)聯(lián)值(Associated Values):
//定義了一個(gè)Barcode的枚舉類(lèi)型,成員值有兩個(gè)荣回,一個(gè)是枚舉成員是UPCA福澡,還有一個(gè)枚舉成員是QRCode,關(guān)聯(lián)值是枚舉成員中的關(guān)聯(lián)出來(lái)的值
enum Barcode{
case UPCA(Int,Int,Int,Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 7, 5, 6)
productBarcode = .QRCode("wocalei")
枚舉值同時(shí)只能存儲(chǔ)這兩個(gè)關(guān)聯(lián)值中的一個(gè)驹马,最后被賦值的會(huì)覆蓋前面的值
可以用一個(gè)switch的語(yǔ)句來(lái)做判斷,這時(shí)候可以給每個(gè)關(guān)聯(lián)值做一個(gè)變量的定義除秀,下面就可以使用這個(gè)變量了
switch productBarcode{
case .UPCA(let wo,let da,let ge,let nihao):
print("\\(wo),\\(da),\\(ge),\\(nihao)")
case .QRCode(var hah):
print("\\(hah)")
}
也可以吧let(var)移到最前面糯累,寫(xiě)成這樣:
//case let .UPCA(wo,da,ge,nihao)
原始值(Raw Values):
作為關(guān)聯(lián)值的替代,枚舉成員可以使用原始值(默認(rèn)值)預(yù)填充册踩,這些原始值的類(lèi)型必須要相同的類(lèi)型
enum ACSIIControl:Character{
case Tab = "\\t"
case LineFeed = "\\n"http://換行
case CarriageReturn = "\\r"http://回車(chē)
}
原始值可以是字符串泳姐,字符,活著任何整型或者浮點(diǎn)類(lèi)型暂吉,每個(gè)原始值在枚舉聲明中必須是唯一的胖秒,當(dāng)整型值被用于原始值,如果其他值沒(méi)有被賦值慕的,她們會(huì)自動(dòng)遞增
enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
let earthOrader = Planet.Earth.rawValue //earthOrader值為3
let possiblePlant = Planet(rawValue: 7)
因?yàn)椴皇撬械腎nt值都可以找到匹配的行星阎肝,這是一個(gè)構(gòu)造函數(shù),可以反回一個(gè)可選的枚舉成員肮街,所以possiblePlant是Planet风题?(可選的Planet),當(dāng)有值的時(shí)候反回可選值嫉父,沒(méi)有就反回nil
let positionTofind = 9
if let somePlanet = Planet(rawValue: positionTofind){
switch somePlanet{
case .Earth:
println("mostly harmless")
default:
println("Not a safe place for humans")
}
}else {
println("There isn't a planet at position \\(positionTofind)")
}
上面這個(gè)例子通過(guò)原始值來(lái)獲得一個(gè)可選的行星沛硅,如果有值救火進(jìn)入if 判斷,如果沒(méi)有就會(huì)進(jìn)入else分支绕辖,顯然上面是沒(méi)有的摇肌,打出There isn't a planet at position 9