从符合 Decodable 协议的 class 派生的 class 会产生编译器错误“Class 'CardListResponse' 没有初始化程序”

a class derived from a class compliant with Decodable protocol yields a compiler error 'Class 'CardListResponse' has no initializers'

public struct CodeAndDetails: Codable {
    public let html: String
    public var code: String

    private enum CodingKeys: String, CodingKey {
        case html = "DETAILS", code = "CODE"
    }

    public func getMessage(font: UIFont) -> NSAttributedString? {
        let res = NSAttributedString(html: html, font: font)
        return res
    }
}

public class BaseResponse: Decodable {

    enum CodingKeys: String, CodingKey {
        case successDetails = "Success"
    }
    public let successDetails: [CodeAndDetails]
}

此处:

public class CardListResponse: BaseResponse {
    public let cards: [DebitCard]?
    public let activeCardId: Int?

    enum CodingKeys: String, CodingKey {
        case cards = "row"
        case activeCardId = "CurrentActiveId"
    }
}

我得到:

Class 'CardListResponse' has no initializers

我有什么选择来处理这个 swift 自负?

问题转移到了运行时。妹子问题在这里:

您应该将 CardListResponse 属性设置为 var 而不是 let

  • let 是常量,这意味着您无法更改值

你能做什么?

  • 您可以将默认值设置为 cardsactiveCardId 属性,例如:

    public class CardListResponse: BaseResponse {
        public let cards: [DebitCard]? = nil
        public let activeCardId: Int? = nil
    
        enum CodingKeys: String, CodingKey {
            case cards = "row"
            case activeCardId = "CurrentActiveId"
        }
    }
    

  • 您可以将 let 更改为 var,例如:

    public class CardListResponse: BaseResponse {
        public var cards: [DebitCard]?
        public var activeCardId: Int?
    
        enum CodingKeys: String, CodingKey {
            case cards = "row"
            case activeCardId = "CurrentActiveId"
        }
    }
    

希望一切顺利。

尽情享受吧。