第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

慕桂英4014372 2019-10-28 16:33:24
使用類繼承是否會(huì)破壞類的可解碼性。例如下面的代碼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現(xiàn)在,如果我將其反轉(zhuǎn),則名稱會(huì)解碼,而id不會(huì)。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而且您不能在兩個(gè)類中都表示Codable。
查看完整描述

3 回答

?
慕桂英3389331

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊

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)

}

對(duì)于解碼,我這樣做:


 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


}


查看完整回答
反對(duì) 回復(fù) 2019-10-28
  • 3 回答
  • 0 關(guān)注
  • 1057 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)