Usando Decodable in Swift 4 con Ereditarietà

L’uso dell’ereditarietà di class dovrebbe rompere la decodificabilità della class. Ad esempio, il seguente codice

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 Development print(item.id ?? "id is nil") print(item.name ?? "name is nil") here 

l’output è:

 1 name is nil 

Ora se inverto questo, decodifica il nome ma l’ID no.

 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 Development print(item.id ?? "id is nil") print(item.name ?? "name is nil") 

l’output è:

 id is nil Large Building Development 

E non puoi esprimere Codificabile in entrambe le classi.