Swift 枚举(Enumerations)

枚举定义了一个通用类型的一组相关值,使你可以在你的代码中以一种安全的方式来使用这些值。

如果你熟悉 C 语言,你就会知道,在 C 语言中枚举将枚举名和一个整型值相对应。Swift 中的枚举更加灵活,不必给每一个枚举成员提供一个值。如果给枚举成员提供一个值(称为“原始”值),则该值的类型可以是字符串,字符,或是一个整型值或浮点数。

此外,枚举成员可以指定任何类型的相关值存储到枚举成员值中,就像其他语言中的联合体(unions)和变体(variants)。你可以定义一组通用的相关成员作为枚举的一部分,每一组都有不同的一组与它相关的适当类型的数值。

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

欲了解更多相关信息,请参见属性(Properties)方法(Methods)构造过程(Initialization)扩展(Extensions)协议(Protocols)

枚举语法

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

enum SomeEnumeration {
  // enumeration definition goes here
}

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

enum CompassPoint {
  case North
  case South
  case East
  case West
}

一个枚举中被定义的值(例如 NorthSouthEastWest)是枚举的成员值(或者成员)。case关键词表明新的一行成员值将被定义。

注意:
和 C 和 Objective-C 不同,Swift 的枚举成员在被创建时不会被赋予一个默认的整型值。在上面的CompassPoints例子中,NorthSouthEastWest不会隐式地赋值为了0123。相反的,这些不同的枚举成员在CompassPoint的一种显示定义中拥有各自不同的值。

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

enum Planet {
  case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

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

var directionToHead = CompassPoint.West

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

directionToHead = .East

directionToHead的类型已知时,再次为其赋值可以省略枚举名。使用显式类型的枚举值可以让代码具有更好的可读性。

匹配枚举值和Switch语句

你可以使用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")
}
// 输出 "Watch out for penguins”

你可以这样理解这段代码:

“判断directionToHead的值。当它等于.North,打印“Lots of planets have a north”。当它等于.South,打印“Watch out for penguins”。”

等等以此类推。

正如在控制流(Control Flow)中介绍的那样,在判断一个枚举类型的值时,switch语句必须穷举所有情况。如果忽略了.West这种情况,上面那段代码将无法通过编译,因为它没有考虑到CompassPoint的全部成员。强制性全部穷举的要求确保了枚举成员不会被意外遗漏。

当不需要匹配每个枚举成员的时候,你可以提供一个默认default分支来涵盖所有未明确被提出的枚举成员:

let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
    print("Mostly harmless")
default:
    print("Not a safe place for humans")
}
// 输出 "Mostly harmless”

相关值(Associated Values)

上一小节的例子演示了如何定义(分类)枚举的成员。你可以为Planet.Earth设置一个常量或者变量,并且在赋值之后查看这个值。不管怎样,如果有时候能够把其他类型的相关值和成员值一起存储起来会很有用。这能让你存储成员值之外的自定义信息,并且当你每次在代码中使用该成员时允许这个信息产生变化。

你可以定义 Swift 的枚举存储任何类型的相关值,如果需要的话,每个成员的数据类型可以是各不相同的。枚举的这种特性跟其他语言中的可辨识联合(discriminated unions),标签联合(tagged unions),或者变体(variants)相似。

例如,假设一个库存跟踪系统需要利用两种不同类型的条形码来跟踪商品。有些商品上标有 UPC-A 格式的一维t条形码,它使用数字 0 到 9。每一个条形码都有一个代表“数字系统”的数字,该数字后接 5 个代表“生产代码”的数字,接下来是5位“产品代码”。最后一个数字是“检查”位,用来验证代码是否被正确扫描:

其他商品上标有 QR 码格式的二维码,它可以使用任何 ISO8859-1 字符,并且可以编码一个最多拥有 2,953 字符的字符串:

对于库存跟踪系统来说,能够把 UPC-A 码作为三个整型值的元组,和把 QR 码作为一个任何长度的字符串存储起来是方便的。

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

enum Barcode {
  case UPCA(Int, Int, Int, Int)
  case QRCode(String)
}

以上代码可以这么理解:

“定义一个名为Barcode的枚举类型,它可以是UPCA的一个相关值(IntIntIntInt),或者是QRCode的一个字符串类型(String)相关值。”

这个定义不提供任何IntString的实际值,它只是定义了,当Barcode常量和变量等于Barcode.UPCABarcode.QRCode时,相关值的类型。

然后可以使用任何一种条码类型创建新的条码,如:

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

以上例子创建了一个名为productBarcode的变量,并且赋给它一个Barcode.UPCA的相关元组值(8, 85909, 51226, 3)

同一个商品可以被分配给一个不同类型的条形码,如:

productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

这时,原始的Barcode.UPCA和其整数值被新的Barcode.QRCode和其字符串值所替代。条形码的常量和变量可以存储一个.UPCA或者一个.QRCode(连同它的相关值),但是在任何指定时间只能存储其中之一。

像以前那样,不同的条形码类型可以使用一个 switch 语句来检查,然而这次相关值可以被提取作为 switch 语句的一部分。你可以在switch的 case 分支代码中提取每个相关值作为一个常量(用let前缀)或者作为一个变量(用var前缀)来使用:

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).")
}
// 输出 "QR code: ABCDEFGHIJKLMNOP."

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

switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
    print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
    print("QR code: \(productCode).")
}
// 输出 "QR code: ABCDEFGHIJKLMNOP."

原始值(Raw Values)

相关值小节的条形码例子中演示了一个枚举的成员如何声明它们存储不同类型的相关值。作为相关值的另一种选择,枚举成员可以被默认值(称为原始值)赋值,其中这些原始值具有相同的类型。

这里是一个枚举成员存储 ASCII 码的例子:

enum ASCIIControlCharacter: Character {
    case Tab = "\t"
    case LineFeed = "\n"
    case CarriageReturn = "\r"
}

在这里,ASCIIControlCharacter的枚举类型的原始值类型被定义为字符型Character,并被设置了一些比较常见的 ASCII 控制字符。字符值的描述请详见字符串和字符部分。

原始值可以是字符串,字符,或者任何整型值或浮点型值。每个原始值在它的枚举声明中必须是唯一的。

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

原始值的隐式赋值(Implicitly Assigned Raw Values)

在使用原始值为整数或者字符串类型的枚举时,不需要显式的为每一个成员赋值,这时,Swift将会自动为你赋值。

例如,当使用整数作为原始值时,隐式赋值的值依次递增1。如果第一个值没有被赋初值,将会被自动置为0。

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

enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

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

当使用字符串作为枚举类型的初值时,每个枚举成员的隐式初值则为该成员的名称。

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

enum CompassPoint: String {
    case North, South, East, West
}

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

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

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

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

使用原始值来初始化(Initializing from a Raw Value)

使用原始值初始化枚举变量(Initializing from a Raw Value)

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

这个例子通过原始值7从而创建枚举成员:

let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet 类型为 Planet? 值为 Planet.Uranus

然而,并非所有可能的Int值都可以找到一个匹配的行星。正因为如此,构造函数可以返回一个可选的枚举成员。在上面的例子中,possiblePlanetPlanet?类型,或“可选的Planet”。

注意:
原始值构造器是一个可失败构造器,因为并不是每一个原始值都有与之对应的枚举成员。更多信息请参见可失败构造器

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

let positionToFind = 9
if let somePlanet = Planet(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

这个范例使用可选绑定(optional binding),通过原始值9试图访问一个行星。if let somePlanet = Planet(rawValue: 9)语句获得一个可选Planet,如果可选Planet可以被获得,把somePlanet设置成该可选Planet的内容。在这个范例中,无法检索到位置为9的行星,所以else分支被执行。

递归枚举(Recursive Enumerations)

在对操作符进行描述的时候,使用枚举类型来对数据建模很方便,因为需要考虑的情况固定可枚举。操作符可以将两个由数字组成的算数表达式连接起来,例如,将5连接成复杂一些的表达式5+4.

算数表达式的一个重要特性是,表达式可以嵌套使用。例如,表达式(5 + 4) * 2乘号右边是一个数字,左边则是另一个表达式。因为数据是嵌套的,因而用来存储数据的枚举类型也许要支持这种嵌套————这表示枚举类型需要支持递归。

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

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

enum ArithmeticExpression {
    case Number(Int)
    indirect case Addition(ArithmeticExpression, ArithmeticExpression)
    indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}

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

indirect enum ArithmeticExpression {
    case Number(Int)
    case Addition(ArithmeticExpression, ArithmeticExpression)
    case Multiplication(ArithmeticExpression, ArithmeticExpression)
}

上面定义的枚举类型可以存储三种算数表达式:纯数字、两个表达式的相加、两个表达式相乘。Addition和 Multiplication成员的相关值也是算数表达式————这些相关值使得嵌套表达式成为可能。

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

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))
// 输出 "18"

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"Swift 3 Functional Programming" English | ISBN: 1785883887 | 2016 | Bring the power of Swift functional programming to iOS, OS X and Web development to build clean, smart and reliable applications About This Book Written for Swift 3, this is a comprehensive guide that introduces iOS and OS X developers to the all-new world of functional programming that has so far been alien to them Learn about first-class functions and how imperative-style patterns can be converted into functional code using some simple techniques The book will get you familiar with using functional programming alongside existing OOP techniques so you can get the best of both worlds and develop clean, robust code Who This Book Is For The book is for iOS, Web, and macOS developers with a basic knowledge of Swift programming that are interested in learning functional programming paradigms What You Will Learn First-class, higher-order, and pure functions Closures and capturing values Custom operators, recursion, and memoization Value and reference types in Swift Enumerations, algebraic data types, patterns, and pattern matching Generics and associated type protocols Higher-order functions such as map, flatMap filter, and reduce Dealing with optionals, fmap, and apply for multiple functional mapping Functional data structures such as Semigroup, Monoid, Binary Search Tree, Linked List, Stack, and Lazy List Immutability, copy constructors, and lenses Combining FP paradigms with OOP, FRP, and POP in your day-to-day development activities Developing a backend application with Swift Developing an iOS application with FP, OOP, FRP, and POP paradigms In Detail Functional programming is getting a lot of attention because it eases many of the difficulties faced in object-oriented programming (OOP) such as testability, maintainability, scalability, and concurrency. Swift has a lot of functional programming features that can be easily used, but most Objective-C and Swift programmers are not familiar with these tools. This book aims at simplifying the functional programming paradigms and makes it easily usable for Swift programmers, by showing you how to use functional programming paradigms to solve many of your day-to-day development problems. Whether you are new to functional programming and Swift, or experienced, this book will strengthen the skills you need to design and develop high-quality, easily maintainable, scalable, extendable, and efficient applications for iOS, Web, macOS, tvOS, and WatchOS. The book starts with functional programming concepts, the basics of Swift, and essential concepts such as functions, closures, optionals, enumerations, immutability, and generics in detail with coding examples. Also, this book introduces more advanced topics such as function composition, functional data structures, monads, functors, applicative functors, memoization, lenses, algebraic data types, functional reactive programming (FRP), protocol-oriented programming (POP), and mixing object-oriented programming (OOP) with functional programming (FP) paradigms. Finally, this book provides a working code example of a real-world frontend application developed with these techniques and its corresponding backend application developed with Swift.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值