亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在帶有繼承的Swift 4中使用Decodable

在帶有繼承的Swift 4中使用Decodable

慕尼黑5688855 2019-12-12 14:10:41
使用類繼承是否會破壞類的可解碼性。例如下面的代碼class Server : Codable {    var id : Int?}class Development : Server {    var name : String?    var userId : Int?}var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"let jsonDecoder = JSONDecoder()let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Developmentprint(item.id ?? "id is nil")print(item.name ?? "name is nil") here輸出為:1name is nil現在,如果我將其反轉,則名稱會解碼,而id不會。class Server {    var id : Int?}class Development : Server, Codable {    var name : String?    var userId : Int?}var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"let jsonDecoder = JSONDecoder()let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Developmentprint(item.id ?? "id is nil")print(item.name ?? "name is nil")輸出為:id is nilLarge Building Development而且您不能在兩個類中都表示Codable。
查看完整描述

3 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

override func encode(to encoder: Encoder) throws {

    try super.encode(to: encoder)

    var container = encoder.container(keyedBy: CodingKeys.self)

    try container.encode(employeeID, forKey: .employeeID)

}

對于解碼,我這樣做:


 required init(from decoder: Decoder) throws {


    try super.init(from: decoder)


    let values = try decoder.container(keyedBy: CodingKeys.self)

    total = try values.decode(Int.self, forKey: .total)

  }


private enum CodingKeys: String, CodingKey

{

    case total


}



查看完整回答
反對 回復 2019-12-13
  • 3 回答
  • 0 關注
  • 437 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號