The code below works in Xcode 9.2 (Swift 4.0) but gives an error in Xcode 9.3 (Swift 4.1).
let dict: [String: Any] = [
"status_code": 5,
"status_message": "message"
]
let data = try! JSONEncoder().encode(dict)
// ^ generic parameter 'T' could not be inferred
I've tried making the dictionary [String: Encodable]
, and using a typealias
to both dictionary types, with the same results. Swift doesn't let you specify the type in a generic call, so that gives a compiler error. What should this look like in Swift 4.1?
A lot of Swift's built-in types already conform to Codable by default. For example, Int , String , and Bool are Codable out of the box. Even dictionaries and arrays are Codable by default as long as the objects that you store in them conform to Codable .
JSONEncoder is an object that encodes instances of a data type as JSON objects. JSONEncoder supports the Codable object. // Encode datalet jsonEncoder = JSONEncoder()
In Swift 4.1 a Dictionary<Key, Value>
conforms to Encodable
only if Key
and Value
are Encodable
themselves.
Examples of Encodable(s)
dictionaries
[String:Int]
[String:String]
[String:Double]
Example of non Encodable(s)
dictionaries
[String:Any]
[String:UIView]
So, how can you solve your problem?
Using a model value is probably the best solution
struct Status: Codable {
let statusCode: Int
let statusMessage: String
}
let status = Status(statusCode: 45, statusMessage: "message")
let data = try? JSONEncoder().encode(status)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With