標籤:switch enum string swift extension
import Foundation//MARK:-------枚舉文法-----------//不像 C 和 Objective-C 一樣,Swift 的枚舉成員在被建立時不會被賦予一個預設的整數值enum CompassPoint{ case North case South case East case West}enum Planet{ case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Nepturn}var directionToHead = CompassPoint.WestdirectionToHead = .Eastswitch directionToHead{ case .North: print("北方") case .South: print("南方") case .East: print("東方") case .West: print("西方") default: print("未知方向")}//MARK:-------執行個體值(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 let .UPCA(numberSystem, identifier, check): print("UPC-A with value of \(numberSystem), \(identifier), \(check).") case let .QRCode(productCode): print("QR code with value of \(productCode).")}// 輸出 "QR code with value of ABCDEFGHIJKLMNOP.//MARK:-------原始值(Raw Values)-----------//原始值可以是字串,字元,或者任何整型值或浮點型值。每個原始值在它的枚舉聲明中必須是唯一的。當整型值被用於原始值,如果其他枚舉成員沒有值時,它們會自動遞增。enum PlanetRaw: Int{ case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}//使用枚舉成員的toRaw方法可以訪問該枚舉成員的原始值:let earthsOrder = PlanetRaw.Earth.rawValueprint(earthsOrder)// earthsOrder is 3//MARK:-----------GCD示範----------var array = ["jack", "rose", "jay", "grace"];//聲明一個全域並發隊列,類型是 dispatch_queue_t;DISPATCH_QUEUE_PRIORITY_DEFAULT為隊列優先順序,預設為0var queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)//開啟一個線程dispatch_async(queue, { () -> Void in print(NSThread.currentThread().isMainThread ? "這是主線程" : "這是後台線程") //第一個參數為次數;第三個參數 block塊裡面的形參是區分第幾次。 dispatch_apply(array.count, queue, { (index:Int) -> Void in print(String(index) + " --- " + array[Int(index)]) }) //回調主線程,執行UI更新 dispatch_async(dispatch_get_main_queue(), { () -> Void in print(NSThread.currentThread().isMainThread ? "這是主線程" : "這是後台線程") })})
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Swift教程之枚舉文法