【问题标题】:Encode and Decode enum in Swift 1.2在 Swift 1.2 中编码和解码枚举
【发布时间】:2015-05-24 08:15:05
【问题描述】:

我的 Swift 类中有一个 enum 并声明了一个变量。我需要使用NSCoder 对其进行编码和解码。关于这句话有很多问题,我应该使用rawValueEnum 声明如下:

enum ConnectionType {
    case Digital, PWM
}

但是在 Swift 1.2 中没有这样的初始化器。如何在 Swift 1.2 和 Xcode 6.3 中做到这一点?

【问题讨论】:

    标签: ios swift nscoder


    【解决方案1】:

    你必须为枚举定义一个“原始类型”,例如

    enum ConnectionType : Int {
        case Digital, PWM
    }
    

    然后你可以用它编码

    aCoder.encodeInteger(type.rawValue, forKey: "type")
    

    并使用解码

    type = ConnectionType(rawValue: aDecoder.decodeIntegerForKey("type")) ?? .Digital
    

    其中 nil-coalescing 运算符 ?? 用于提供默认值 如果解码的整数对枚举无效。

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2020-08-10
      • 2022-06-16
      • 1970-01-01
      相关资源
      最近更新 更多