gpt4 book ai didi

iOS( swift ): Encoding/Decoding Enums

转载 作者:行者123 更新时间:2023-11-28 14:25:43 24 4
gpt4 key购买 nike

我有一些 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 的定义时,出现以下错误 Argument of '#keyPath' refers to non-'@objc' property 'direction'

@objc public var direction: Direction

我收到错误消息Property cannot be marked @objc because its type cannot be represented in Objective-C

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

感谢您的帮助。

编辑

评论说明了问题。此链接中的答案建议如何使用 String 原始表示来完成。

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

最佳答案

您可以利用基于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)
}

关于iOS( swift ): Encoding/Decoding Enums,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51591755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com