[Swift]Day09:枚举

枚举

相关值 - Associated Values

Swift 中的相关值有点像是 F# 中的 Discriminated Unions,它允许在枚举中存储额外的数据。

比如下面这个 Barcode 的例子。枚举类中定义了两种条形码,一种是普通的条形码 UPCA ,存储四个 Int 值;另一种是二维码 QRCode ,存储一个字符串的值:

enum Barcode {
    case UPCA(Int, 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):
    println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
    println("QR code: \(productCode).")
}
// prints "QR code: ABCDEFGHIJKLMNOP."

这个挺有意思,如果我们要比较两个枚举变量,比如 code1 == code2 ,结果是相等还是不等呢?

答案是:都不对。Xcode会报错告诉你 == 符号无法调用。我们可以自定义运算符解决这个问题:

func ==(a:Barcode, b:Barcode) -> Bool {
    switch(a) {

    case let .UPCA(a1,b1,c1,d1):
        switch(b) {
        case let .UPCA(a2,b2,c2,d2):
            return (a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2)
        default:
            return false
        }

    case let .QRCode(a1):
        switch(b) {
        case let .QRCode(a2):
            return a1 == a2
        default:
            return false
        }
    }
}

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

var code1 = Barcode.UPCA(8, 85909, 51226, 3)
var code2 = Barcode.UPCA(8, 85909, 51226, 4)

code1 == code2  // false

如果没有相关值是可以直接比较的:

enum Numbers: Int {
    case One = 1, Two, Three, Four, Five
}
var possibleNum1 = Numbers.Three
var possibleNum2 = Numbers.Three
println(possibleNum1 == possibleNum2) // true

原始值 - Raw Values

我们可以给枚举类型的成员用默认值填充,比如下面这个例子,成员的类型为 Character :

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

原始值可以是 StringCharacterIntFloat,但是只有 Int 可以自增。使用 toRaw 可以访问该枚举成员的原始值:

ASCIIControlCharacter.Tab.rawValue  // rawValue = \t

也可以用 fromRaw 从原始值转换成枚举成员,注意返回的是 .Some ,因为不一定能转换成功:

var a = ASCIIControlCharacter(rawValue: "\t")
a?.rawValue // {Some "\t"}

遍历

我们可以通过 allValues 遍历枚举类型的所有成员:

enum ProductCategory : String {
     case Washers = "washers", Dryers = "dryers", Toasters = "toasters"

     static let allValues = [Washers, Dryers, Toasters]
}

for category in ProductCategory.allValues{
     //Do something
}

用处

用好枚举类型可以有效的提高代码的可读性,比如我们在 prepareForSegue 中经常需要对 segue.segueIdentifier进行比较,如果纯粹的进行字符串比较显得很生硬,不妨在外面套上一层枚举类型,像这样:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if let identifier = SegueIdentifier.fromRaw(segue.identifier) {
        switch identifier {
        case .OtherScreenSegue1:
            println("Going to other screen 1")
        case .OtherScreenSegue2:
            println("Going to other screen 2")
        case .OtherScreenSegue3:
            println("Going to other screen 3")
        default:
            println("Going somewhere else")
        }
    }
}

同理,也可以用在 NSNotificationCenter 里。

其他

发现一个挺好的网站:SwiftExamples,通过例子演示 Swift 的各种语法,如果一时半会的忘了某个语法可以去看一看。


References

时间: 2024-08-01 03:42:25

[Swift]Day09:枚举的相关文章

Swift学习——A Swift Tour 枚举和结构体

Enumerations and Structures Enumerations   枚举的使用 使用 enum 定义一个枚举,枚举里面可以关联方法,比如下文中的描述方法 enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { ca

swift笔记- 枚举

枚举是一系列相关值的通用类型,是类型安全的. Swift中的枚举不需要为每一个成员赋值,而成员的值可以是 字符串 字符 或者人意的整数或浮点值. 枚举成员可以指定任何存储成员值类型的关联值enumeration members can specify associated values of any type to be stored along with each different member value.枚举成员可以是相关的成员集合,而每个成员也可以是一个单独的小集合. 枚举跟传统的类结

Swift 中枚举

Swift 中枚举高级用法及实践 字数11017 阅读479 评论0 喜欢20 title: "Swift 中枚举高级用法及实践"date: 2015-11-20tags: [APPVENTURE]categories: [Swift 进阶]permalink: advanced-practical-enum-examples 原文链接=http://appventure.me/2015/10/17/advanced-practical-enum-examples/作者=Benedik

swift学习——枚举

swift枚举 1. 枚举基本语法 enum Method { case Add case Sub case Mul case Div } 也可以使用一种更简单的写法 enum Method1{ case add, div,mul,sub } 2. swift匹配枚举值 func chooseMethod(op :Method) ->(Double , Double) ->Double { switch op { //.Add其实就是Method.Add case .Add: func add

Swift - 39 - 枚举类型关联默认值

//: Playground - noun: a place where people can play import UIKit enum Month: Int { // 这么定义, 后面的Feb, Mar会自动赋值为2和3.. case Jan = 1, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec } let currentMonth:Month = .Nov // 查看枚举对应的值 currentMonth.rawValue

Swift,枚举

枚举类型判断 1.设置并利用枚举 enum Weacher{ case a case b case c } var d=Weacher.b switch d{ case .a: print("a") case .b: print("b") //b default: print("nil") } 2.利用元组 enum Weacher{ case a(Int,String) case b(Int,String) case c(Int,String)

初学swift笔记 枚举(七)

1 import Foundation 2 3 /* 4 枚举 5 6 语法结构 7 enum 类型 { 8 case 值 9 } 10 */ 11 //定义一个枚举 写法1 12 enum LiuShiQun { 13 case Name 14 case Age 15 case Sex 16 case Add 17 case Sub 18 case Mul 19 case Div 20 } 21 //定义一个枚举 写法2 22 enum LiuShiQun_1 { 23 case Add,Su

swift 定义枚举和结构体 及使用

//定义枚举 enum MapDirection { case North case South case East case West func simpleDescription() -> String { switch self { case .North: return "North" case .South: return "South" case .East: return "East" case .West: return &

iOS二次发育(swift)枚举

//: Playground - noun: a place where people can play import UIKit //Raw Value enum Month: String{ case January = "Value_January" case February = "Value_February" case March = "Value_March" case April = "Value_April"