There is the following code, but it does not work as expected because Swift gives errors.

import UIKit enum ObjectStatus: String, Codable { case Arm = "Arm" case Disarm = "Disarm" } struct Testobject: Codable { var id: Int var name: String? var city: String var status: ObjectStatus //var active: Bool } func decodejson<T>(_ value:String) -> T? { let jsonDecoder = JSONDecoder() let decode = try jsonDecoder.decode(T.self as! Codable, from: input_json.data(using: String.Encoding.utf8)!) dump(decode) } let input_json = "{\"status\": \"Arm\", \"id\" : 1,\"name\" : null,\"city\" : \"Moscow\", \"active\": true}" if let my_object = decodejson<Testobject>(input_json) { dump(my_object) } 

I am trying to write one decoding function and pass json and the type of target object into which json should be decoded. That would not write for each object its decoding function

    1 answer 1

    you do not have a return in func decodejson + type Т may not answer Codable and you incorrectly called the generic function (it needs to explicitly specify the type of the return value)

     enum ObjectStatus: String, Codable { case Arm = "Arm" case Disarm = "Disarm" } struct Testobject: Codable { var id: Int var name: String? var city: String var status: ObjectStatus //var active: Bool } func decodejson<T: Codable>(_ value:String) -> T? { let jsonDecoder = JSONDecoder() let decode = try? jsonDecoder.decode(T.self, from: input_json.data(using: String.Encoding.utf8)!) dump(decode) return decode } let input_json = "{\"status\": \"Arm\", \"id\" : 1,\"name\" : null,\"city\" : \"Moscow\", \"active\": true}" if let my_object: Testobject = decodejson(input_json) { dump(my_object) } 
    • This is what you need. In my experience in C #, where <T> does not need to indicate what answers and simply encodes / decodes the object, regardless of type, Swift is misleading in using <T> - Gennady Kurbesov
    • I'm not sure if I understand you correctly decodejson<T: Codable> and if you use C #, this is a type restriction and judging by what is described here docs.microsoft.com/ru-ru/dotnet/csharp/programming-guide/... restriction The type is also quite often used in C #. And in this case, JSONDecoder().decode accepts only the type Decodable or Codable which includes Decodable - Andrey Iskamov
    • Almost, but more precisely, in c #, the serialization and deserialization of an object in json or xml does not require an indication of any type or interface (protocol) and therefore you can simply write <T>. Expectations from the swift of the same functionality and led astray - Gennady Kurbesov