ios - 当 JSON 输入表示 Codable 类型的多个子类时使用 Codable

标签 ios json swift swift4 codable

假设我有一些 JSON,如下所示:

{ 
  "some-random-key": { 
                       "timestamp": 1234123423
                       "type": "text",
                       "content": "Hello!" 
                     },

  "some-other-key": { 
                      "timestamp": 21341412314
                      "type": "image",
                      "path": "/path/to/image.png" 
                    }
}

此 JSON 代表两个消息对象。这是我想如何表示它们(Swift 4):

class Message: Codable {
    let timestamp: Int
    // ...codable protocol methods...
}

class TextMessage: Message {    // first message should map to this class

    let content: String

    // ...other methods, including overridden codable protocol methods...
}

class ImageMessage: Message {    // second message should map to this class
    let path: String

    // ...other methods, including overridden codable protocol methods...
}

如何使用 JSON 中的“type”属性来告诉 Codable 要初始化哪个子类?我的第一直觉是使用枚举作为中介,这将允许我在字符串表示和元类型之间切换

enum MessageType: String {
    case image = "image"
    case text = "text"

    func getType() -> Message.Type {
        switch self {
        case .text: return TextMessage.self
        case .image: return ImageMessage.self
        }
    }

    init(type: Message.Type) {
        switch type {
        case TextMessage.self: self = .text
        case ImageMessage.self: self = .image
        default: break
        }
    }
}

但是,这里的init会导致编译错误-
“TextMessage.Type”类型的表达式模式无法匹配“Message.Type”类型的值
是否有规范/公认的方法来处理这种情况?为什么 getType 函数编译时这里的 init 编译不了?

最佳答案

我会采用这种方法:

static func createMessage(with json: [String: Any]) -> Message? {
       guard let typeString = json["type"] as? String,
       let type = MessageType(rawValue: typeString) else { return nil }
       switch type {
       case .image: return ImageMessage(....

等等

关于ios - 当 JSON 输入表示 Codable 类型的多个子类时使用 Codable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498751/

相关文章:

ios - 我如何使用 Swift 格式化这些数据以便后端可以读取它?

iphone - 根据纬度和经度得到错误的排序距离

java - openapi generator maven plugin可空属性问题

php - "Javascript"能否解密由 PHP 加密的数据?

swift,如何从另一个函数中检索字符串?

ios - Xcode:如何将图像尺寸保持在纵向和横向之间 - 不调整大小

objective-c - Core Data 整数使用哪些整数类型

UITabBarItem 中的 iOS 自定义动画

ios - 如何在UIpickerView的特定行中插入图像和文本?

java - 获取要 curl 的字符串有效负载