【问题标题】:iOS (Swift): Encoding/Decoding EnumsiOS (Swift):编码/解码枚举
【发布时间】:2019-01-06 13:45:58
【问题描述】:

我有一些 NSObject 的子类,它定义了一个可表示的字符串 Enum,如下所示:

class SomeClass: NSObject {

    enum Direction: String {
        case north = "North"
        case south = "South"
    }

    public var direction: Direction

    init(direction: Direction) {
        self.direction = direction
        super.init()
    }

}

我想让这个类被编码和解码,所以我使用如下:

func encode(with aCoder: NSCoder) {
    aCoder.encode(direction, forKey: #keyPath(direction))
}

public convenience required init?(coder aDecoder: NSCoder) {
    self.init(direction: aDecoder.decodeObject(forKey: #keyPath(direction)) as! Direction)
}

但是,当我将direction 的定义更改为

@objc public var direction: Direction

我收到错误属性不能被标记为@objc,因为它的类型不能在Objective-C中表示

请问避免这个错误的最佳方法是什么?

感谢您的帮助。

编辑

cmets 解释了这个问题。此链接中的此答案建议如何使用 String 原始可表示来完成。

How to make a Swift String enum available in Objective-C?

【问题讨论】:

  • 尝试用@objc标记你的enum Direction
  • @Tj3n 谢谢...我现在得到以下 '@objc' 枚举原始类型 'String' 不是整数类型
  • 在 objc 中没有带字符串的枚举,您必须使用 Int 枚举和另一个函数/计算变量将其转换为字符串

标签: ios swift enums encode


【解决方案1】:

您可以利用基于String 的枚举(不仅如此)具有的rawValue 支持:

func encode(with aCoder: NSCoder) {
    aCoder.encode(direction.rawValue, forKey: "direction")
}

public convenience required init?(coder aDecoder: NSCoder) {
    guard let direction = Direction(rawValue: aDecoder.decodeObject(forKey: "direction") else {
        // direction was not encoded, we assume an encoding error
        return nil
    }
    self.init(direction: direction)
}

【讨论】:

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