美文网首页小斑iOS-swift
Swift enum(枚举)使用范例

Swift enum(枚举)使用范例

作者: 老马的春天 | 来源:发表于2017-01-03 14:56 被阅读188次
    //: Playground - noun: a place where people can play
    
    import UIKit
    
    var str = "Hello, playground"
    
    enum Movement {
        case Left
        case Right
        case Top
        case Bottom
    }
    
    let aMovement = Movement.Left
    
    switch aMovement {
    case .Left:
        print("left")
    default:
        print("Unknow")
    }
    
    if case .Left = aMovement {
        print("Left")
    }
    
    if .Left == aMovement {
        print("Left")
    }
    
    enum Season: Int {
        case Spring = 0
        case Summer = 1
        case Autumn = 2
        case Winter = 3
    }
    
    enum House: String {
        case ZhangSan = "I am zhangsan"
        case LiSi = "I am lisi"
    }
    
    let zs = House.ZhangSan
    print(zs.rawValue)
    
    enum Constants: Double {
        case π = 3.14159
        case e = 2.71828
        case φ = 1.61803398874
        case λ = 1.30357
    }
    
    let pai = Constants.π
    print(pai.rawValue)
    
    
    enum CompassPoint: String {
        case North, South, East, West
    }
    
    let n = CompassPoint.North
    print(n.rawValue)
    
    let s = CompassPoint(rawValue: "South");
    
    
    enum VNodeFlags : UInt32 {
        case Delete = 0x00000001
        case Write = 0x00000002
        case Extended = 0x00000004
        case Attrib = 0x00000008
        case Link = 0x00000010
        case Rename = 0x00000020
        case Revoke = 0x00000040
        case None = 0x00000080
    }
    
    enum Character {
        
        enum Weapon {
            case Bow
            case Sword
            case Lance
            case Dagger
        }
        
        enum Helmet {
            case Wooden
            case Iron
            case Diamond
        }
        
        case Thief
        case Warrior
        case Knight
    }
    
    let character = Character.Thief
    let weapon = Character.Weapon.Bow
    let helmet = Character.Helmet.Iron
    
    
    struct Scharacter {
        enum CharacterType {
            case Thief
            case Warrior
            case Knight
        }
        
        enum Weapon {
            case Bow
            case Sword
            case Lance
            case Dagger
        }
        
        let type: CharacterType
        let weapon: Weapon
    }
    
    let sc = Scharacter(type: .Thief, weapon: .Bow)
    print(sc.type)
    
    
    enum Trade {
        case Buy(stock: String, amount: Int)
        case Sell(stock: String, amount: Int)
    }
    
    let trade = Trade.Buy(stock: "Car", amount: 100)
    if case let Trade.Buy(stock, amount) = trade {
        print("buy \(amount) of \(stock)")
    }
    
    enum Trade0 {
        case Buy(String, Int)
        case Sell(String, Int)
    }
    
    let trade0 = Trade0.Buy("Car0", 100)
    if case let Trade0.Buy(stock, amount) = trade0 {
        print("buy \(amount) of \(stock)")
    }
    
    
    enum Wearable {
        enum Weight: Int {
            case Light = 2
        }
        
        enum Armor: Int {
            case Light = 2
        }
        
        case Helmet(weight: Weight, armor: Armor)
        
        
        func attributes() -> (weight: Int, armor: Int) {
            switch self {
            case .Helmet(let w, let a):
                return (weight: w.rawValue * 2, armor: a.rawValue * 4)
      
            }
        }
    }
    
    let test = Wearable.Helmet(weight: .Light, armor: .Light).attributes()
    print(test)
    
    enum Device {
        case iPad, iPhone, AppleTV, AppleWatch
        func introduced() -> String {
            switch self {
            case .AppleTV: return "\(self) was introduced 2006"
            case .iPhone: return "\(self) was introduced 2007"
            case .iPad: return "\(self) was introduced 2010"
            case .AppleWatch: return "\(self) was introduced 2014"
            }
        }
    }
    print (Device.iPhone.introduced())
    
    
    
    enum Device1 {
        case iPad, iPhone
        var year: Int {
            switch self {
            case .iPad:
                return 2010
            case .iPhone:
                return 2007
        }
        }
    }
    
    let iPhone = Device1.iPhone
    print(iPhone.year)
    
    
    
    enum Device2 {
        case AppleWatch
        
        static func fromSlang(term: String) -> Device2? {
            if term == "iWatch" {
                return .AppleWatch
            }
            return nil
        }
    }
    
    print(Device2.fromSlang(term: "iWatch") ?? "nil")
    
    
    enum TriStateSwitch {
        case Off, Low, High
        
        mutating func next() {
            switch self {
            case .Off:
                self = .Low
            case .Low:
                self = .High
            case .High:
                self = .Off
        }
        }
    }
    
    var state = TriStateSwitch.Low // 必须使用var
    state.next()
    state.next()
    
    
    protocol CustomStringConvertible {
        var description: String { get }
    }
    
    enum Trade1: CustomStringConvertible {
        case Buy, Sell
        var description: String {
            switch self {
            case .Buy:
                return "We're buying something"
            case .Sell:
                return "We're selling something"
        }
        }
    }
    
    let t1 = Trade1.Buy.description
    
    
    protocol AccountCompatible {
        var remainingFunds: Int { get }
        mutating func addFunds(amount: Int) throws
        mutating func removeFunds(amount: Int) throws
    }
    
    enum Account {
        case Empty
        case Funds(remaining: Int)
        
        enum ErrorInfo: Error {
            case OverDraft(amount: Int)
        }
        
        var remainingFunds: Int {
            switch self {
            case .Empty:
                return 0
            case .Funds(let remaining):
                return remaining
        }
        }
    }
    
    extension Account: AccountCompatible {
        mutating func addFunds(amount: Int) throws {
            var newAmount = amount
            if case let .Funds(remaining) = self {
                newAmount += remaining
            }
            
            if newAmount < 0 {
                throw Account.ErrorInfo.OverDraft(amount: newAmount)
            }else if newAmount == 0 {
                self = .Empty
            }else {
                self = .Funds(remaining: newAmount)
            }
        }
        
        mutating func removeFunds(amount: Int) throws {
            try self.addFunds(amount: amount * -1)
        }
    }
    
    var account = Account.Funds(remaining: 20)
    try? account.addFunds(amount: 20)
    print("add: ", account.remainingFunds)
    try? account.removeFunds(amount: 15)
    print ("remove 1: ", account.remainingFunds)
    
    do {
        try account.removeFunds(amount: 55)
    }catch (let errorInfo)  {
        print(errorInfo)
    }
    print ("remove 2: ",  try? account.removeFunds(amount: 55))
    

    来源:Swift 中枚举高级用法及实践
    Advanced & Practical Enum usage in Swift

    相关文章

      网友评论

        本文标题:Swift enum(枚举)使用范例

        本文链接:https://www.haomeiwen.com/subject/xrqnvttx.html