使用類繼承是否會破壞類的可解碼性。例如下面的代碼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。
在帶有繼承的Swift 4中使用Decodable
慕尼黑5688855
2019-12-12 14:10:41