Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a mixed-value-type dictionary to JSON in Swift 4.1

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?

like image 845
Dov Avatar asked Apr 11 '18 12:04

Dov


People also ask

Is Dictionary Codable in Swift?

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 .

What is JSON encoder in Swift?

JSONEncoder is an object that encodes instances of a data type as JSON objects. JSONEncoder supports the Codable object. // Encode datalet jsonEncoder = JSONEncoder()


1 Answers

Is Dictionary Encodable?

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?

Struct

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)
like image 108
Luca Angeletti Avatar answered Sep 21 '22 09:09

Luca Angeletti