[連載]Swift開發入門(05)--- 枚舉

來源:互聯網
上載者:User

標籤:swift   枚舉   switch   

??枚舉是定義符號常量的手段,它把一堆相似的值組織在一起。例如你在指定文字對齊的時候通常有三種可選的值:靠左對齊、靠右對齊和置中對齊;你在處理遊戲中的方法時可能的取值有東、西、南、北。Swift中的枚舉比你瞭解的其他語言的枚舉更加強大,它的行為類似於類和結構體,它甚至可以有自己的方法,包括構造器。

建立枚舉

??我們先通過一個簡單的例子來認識一下枚舉。玩過撲克牌的都知道,撲克有四種花色,分別是黑桃(spade)、紅心(heart)、草花(club)和方塊(diamond),如果我們要做一個撲克遊戲,那麼就可以用枚舉來描述這四種花色,代碼如下所示:

enum Suite {    case Spade    case Heart    case Club    case Diamond}

??又比如我們要做一個繪圖軟體,該軟體支援繪製矩形、圓形和三角形,那麼可以用下面的枚舉來表示不同類型的圖形。

enum Shape {    case Rectangle    case Triangle    case Circle}
在switch多分支結構中使用枚舉

??我們可以使用switch多分支結構來處理枚舉類型的值,如下所示:

var shape:Shape = Shape.Circleswitch(shape) {case .Rectangle:    println("You choose a rectangle")    breakcase .Triangle:    println("You choose a triangle")    breakcase .Circle:    println("You choose a circle")    break}

??Swift中的switch語句要求必須覆蓋所有的可能,如果你如下書寫上面這段代碼,就會產生一個編譯錯誤:“switch must be exhaustive, consider adding a default clause.”。

var shape:Shape = Shape.Circleswitch(shape) {case .Rectangle:    println("You choose a rectangle")    breakcase .Triangle:    println("You choose a triangle")    break}

??按照錯誤提示,我們可以添加一個default分支來消除此編譯錯誤,當所有的case都沒有匹配成功時,就會執行default分支。

var shape:Shape = Shape.Circleswitch(shape) {case .Rectangle:    println("You choose a rectangle")    breakcase .Triangle:    println("You choose a triangle")    breakdefault:    println("You choose a circle")    break}

??當然也可以在一個case中書寫多種可能性,這一點也是Swift對switch結構的改進,不同於Java、C#、JavaScript這樣的語言,完整的代碼如下所示:

var shape:Shape = Shape.Squareswitch(shape) {case .Rectangle, .Square, .Diamond:    println("You choose a quadrilateral")    breakcase .Triangle:    println("You choose a triangle")    breakcase .Circle, .Oval:    println("You choose a circle or an oval")    break}
枚舉類型

??在Swift中,枚舉在某些程度上跟類和結構體非常類似,它和結構體有相同的值語義,因此也是基於棧分配儲存空間。有些枚舉甚至可以有成員方法,如下所示:

import Foundationenum Shape {    case Rectangle(width: Double, height: Double)    case Square(side: Double)    case Triangle(base: Double, height: Double)    case Circle(radius: Double)    func area() -> Double {        var result:Double = 0;        switch(self) {        case .Rectangle(let width, let height):            result = width * height        case .Square(let side):            result = side * side        case .Triangle(let base, let height):            result = base * height        case .Circle(let radius):            result = M_PI * radius * radius        }        return result    }}var circle = Shape.Circle(radius: 5)circle.area()

??我們還可以在枚舉中添加一個Factory 方法來建立枚舉類型的變數,如下所示:

import Foundationenum Shape {    case Rectangle(width: Double, height: Double)    case Square(side: Double)    case Triangle(base: Double, height: Double)    case Circle(radius: Double)    func area() -> Double {        var result:Double = 0;        switch(self) {        case .Rectangle(let width, let height):            result = width * height        case .Square(let side):            result = side * side        case .Triangle(let base, let height):            result = base * height        case .Circle(let radius):            result = M_PI * radius * radius        }        return result    }    static func factory(shapeType: String) -> Shape? {        var shape:Shape?        switch(shapeType) {            case "rectangle":                shape = Shape.Rectangle(width: 5, height: 10)            case "square":                shape = Shape.Square(side: 5)            case "triangle":                shape = Shape.Triangle(base: 5, height: 10)            case "circle":                shape = Shape.Circle(radius: 5)            default:                shape = nil        }        return shape    }}var rect = Shape.factory("rectangle")rect!.area()

??我們之前講過的可空類型其實也是枚舉類型,它的定義如下所示:

enum Optional<T> : NilLiteralConvertible {    case None    case Some(T)    init()    init(_ some: T)    static func convertFromNilLiteral() -> T?}

[連載]Swift開發入門(05)--- 枚舉

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.