《swift2.0 官方教程中文版》 第2章-08枚举


import Foundation


// Swift ,枚举类型是一等公民(first-class)。它们采用了很多传统上只被类(class)支持的特征,例如 计算型属性(computed properties),用于提供关于枚举当前值的附加信息,实例方法(instance methods),用于提供和枚举所代表的值相关联的功能。枚举也可以定义构造函数(initializers)来提供一个初始值;可以在原始的实现基础上扩展它们的功能;可以遵守协议(protocols)来提供标准的功能



/*枚举语法*********************************************************/

//使用 enum 关键词来创建枚举并且把它们的整个定义放在一对大括号内:

enum SomeEnumeration {

// enumeration deFinition goes here

}


//以下是指南针四个方向的一个例子:

enum Compasspoint {

case north

case South

case East

case West

}


//多个成员值可以出现在同一行上,用逗号隔开:

enum Planet {

case Mercury,Venus,Earth,Mars,Jupiter,Uranus,Neptune;

}

//每个枚举定义了一个全新的类型。像 Swift 中其他类型一样,它们的名字(例如 Compasspoint Planet )必须以一个大写字母开头。给枚举类型起一个单数名字而不是复数名字,以便于读起来更加容易理解:

var directionToHead = Compasspoint.West


//directionToHead 的类型可以在它被 Compasspoint 一个可能值初始化时推断出来。一旦 directionToHead 被声明为一个 Compasspoint,你可以使用一个缩写语法(.)将其设置为另一个 Compasspoint 的值:

directionToHead = .East




/*匹配枚举值 Switch 语句*********************************************************/

directionToHead = .South

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")

}


//在判断一个枚举类型的值时,switch 语句必须穷举所有情况


let somePlanet = Planet.Earth

switch somePlanet {

case .Earth:

print("Mostly harmless")

default:

print("Not a safe place for humans")

}

// 输出 "Mostly harmless”




/*相关值(Associated Values)*********************************************************/

// Swift ,使用如下方式定义两种商品条码的枚举:

enum Barcode {

case UPCA(Int,Int,Int)

case QRCode(String)

}

var productBarcode = Barcode.UPCA(8,85909,51226,3)


productBarcode = .QRCode("ABCDEFGHIJKLMnop")


switch productBarcode {

case .UPCA(let numberSystem,let manufacturer,let product,let check):

print("UPC-A: \(numberSystem),\(manufacturer),\(product),\(check).")

case .QRCode(let productCode):

print("QR code: \(productCode).")

}


//如果一个枚举成员的所有相关值被提取为常量,或者它们全部被提取为变量,为了简洁,你可以只放置一个var或者 let 标注在成员名称:

switch productBarcode {

case let .UPCA(numberSystem,manufacturer,product,check):

print("UPC-A: \(numberSystem),\(check).")

case let .QRCode(productCode):

print("QR code: \(productCode).")

}




/*原始值(Raw Values)*********************************************************/

enum ASCIIControlCharacter: Character {

case Tab = "\t"

case LineFeed = "\n"

case CarriageReturn = "\r"

}


//原始值和相关值是不相同的。当你开始在你的代码中定义枚举的时候原始值是被预先填充的值,像上述三个 AS CII 码。对于一个特定的枚举成员,它的原始值始终是相同的。相关值是当你在创建一个基于枚举成员的新常量 或变量时才会被设置,并且每次当你这么做得时候,它的值可以是不同的。



//下面的枚举是对之前 Planet 这个枚举的一个细化,利用原始整型值来表示每个 planet 在太阳系中的顺序:

enum Planet2: Int {

case Mercury = 1,Saturn,Neptune

}

//在上面的例子中,Plant.Mercury 赋了初值 1,Planet.Venus 会拥有隐式赋值 2,依次类推。


//下面的例子是 Compasspoint 枚举类型的精简版,使用字符串作为初值类型,隐式初始化为每个方向的名称:

enum Compasspoint2: String {

case north,South,East,West

}

//上面例子中,Compasspoint.south 拥有隐式初值 South,依次类推。


//使用枚举成员的 rawValue 属性可以访问该枚举成员的原始值:

let earthsOrder = Planet2.Earth.rawValue // earthsOrder 值为 3

print("earthsOrder is \(earthsOrder)")


let sunsetDirection = Compasspoint2.West.rawValue// sunsetDirection 值为 "West"

print("sunsetDirection is \(sunsetDirection)")


//如果在定义枚举类型的时候使用了原始值,那么将会自动获得一个初始化方法,这个方法将原始值类型作为参 ,返回枚举成员或者nil 。你可以使用这种初始化方法来创建一个新的枚举变量。

let possiblePlanet = Planet2(rawValue: 7)

// possiblePlanet 类型为 Planet? 值为 Planet.Uranus

//原始值构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的枚举成员



//如果你试图寻找一个位置为9的行星,通过参数为rawValue构造函数返回的可选Planet值将是nil

let positionToFind = 9

if let somePlanet = Planet2(rawValue: positionToFind) {

switch somePlanet {

case .Earth:

print("Mostly harmless")

default:

print("Not a safe place for humans")

}

} else {

print("There isn't a planet at position \(positionToFind)")

}

// 输出 "There isn't a planet at position 9




/*递归枚举(Recursive Enumerations)*********************************************************/


//递归枚举(recursive enumeration) 是一种枚举类型,表示它的枚举中,一个或多个枚举成员拥有该枚举的 其他成员作为相关值。使用递归枚举时,编译器会插入一个中间层。你可以在枚举成员前加上 indirect 来表示这 成员可递归。

//例如,下面的例子中,枚举类型存储了简单的算数表达式:

enum ArithmeticExpression {

case Number(Int)

indirect case Addition(ArithmeticExpression,ArithmeticExpression)

indirect case Multiplication(ArithmeticExpression,ArithmeticExpression)

}


//你也可以在枚举类型开头加上 indirect 关键字来表示它的所有成员都是可递归的:

indirect enum ArithmeticExpression2 {

case Number(Int)

case Addition(ArithmeticExpression2,ArithmeticExpression2)

case Multiplication(ArithmeticExpression2,ArithmeticExpression2)

}


//递归函数可以很直观地使用具有递归性质的数据结构。例如,下面是一个计算算数表达式的函数:

func evaluate(expression: ArithmeticExpression) -> Int {

switch expression {

case .Number(let value):

return value

case .Addition(let left,let right):

return evaluate(left) + evaluate(right)

case .Multiplication(let left,let right):

return evaluate(left) * evaluate(right)

}

}


// 计算(5+4)*2

let five = ArithmeticExpression.Number(5)

let four = ArithmeticExpression.Number(4)

let sum = ArithmeticExpression.Addition(five,four)

let product = ArithmeticExpression.Multiplication(sum,ArithmeticExpression.Number(2))

print(evaluate(product))


//函数如果遇到纯数字,就直接返回该数字的值。如果遇到的是加法或乘法元算,则分别计算左边表达式和右边表达式的值,然后相加或相乘。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...