美文网首页
Swift中Enum的使用姿势

Swift中Enum的使用姿势

作者: ba78fbce98d5 | 来源:发表于2016-02-17 01:30 被阅读676次

    Swift的Enum类型可以存储值

    <pre>
    enum iOSDeviceSystemType {
    case iPhone(String)
    case iPad(String)
    case iWatch
    }

    var myDeviceSystem = iOSDeviceSystemType.iPad("9.1")

    switch myDeviceSystem {
    case .iPhone(let model):
    print("My iPhone's System is (model)");
    break
    case .iPad(let model) :
    print("My iPad's System is (model)");
    break
    case .iWatch: print("I had no iWatch, 😄😄😄")
    default:
    print("not an iOS device")
    }
    </pre>

    比较两个枚举值是否相等

    <pre>
    var newDevice = iOSDeviceSystemType.iPhone("9.1")
    var oldDevice = iOSDeviceSystemType.iPhone("8.1")

    newDevice == oldDevice
    </pre>

    系统提示:

    Binary operator '==' cannot be applied to two 'iOSDeviceSystemType' operands

    总结:在Swift中,enum不提供 == 运算符的操作。

    正确姿势:

    使用switch去判断类型

    <pre>
    var newDevice = iOSDeviceSystemType.iPhone("9.1")
    var oldDevice = iOSDeviceSystemType.iPhone("8.1")

    func sameDevice(firstDevice: iOSDeviceSystemType, secondDevice: iOSDeviceSystemType) -> Bool {

    switch (firstDevice, secondDevice) {
        
    case(.iPhone(let a), .iPhone(let b)) where a == b : return true
    
    case(.iPad(let a), .iPhone(let b)) where a == b : return true
    
    case (.iWatch, .iWatch):
        return true
    
    default:
        return false
    }
    

    }

    print(sameDevice(myDeviceSystem, secondDevice: oldDevice))
    </pre>

    默认值

    <pre>
    enum Direction: Int {
    case Up = 1
    case Down
    case Left
    case Right
    }
    </pre>

    使用Row Value创建枚举

    <pre>
    var direction = Direction(rawValue: 4)
    </pre>

    提示: rawValue返回的值,是Optional类型。上述例子返回的是Direction?,并不是Direction类型。


    提示:有时候,点语法不太友好,虽然说姿势最佳的是使用点语法,但是编译器会卡顿,并且不提示,如果没耐心,还是全写来的方便。


    happy coding happy life.
    welcom to my blog.

    相关文章

      网友评论

          本文标题:Swift中Enum的使用姿势

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