Struct to make simple [String: Any] dictionaries conform to Codable.
letdata1:Data=try!Data(contentsOf:Bundle.main.url(forResource:"test", withExtension:"json")!)letdict=try?JSONDecoder().decode(CodableDictionary.self, from: data)letname=dict?["name"]CodableDictionary can be initialised with [String: Any].
letdict=CodableDictionary(value:["foor":233,"nested":["n1":"hallo","n2":"welt","nested":["n1":"hallo","n2":"welt"]]])letencodedData:Data=try!JSONEncoder().encode(dict)letjsonString=String(data: encodedData, encoding:.utf8)Encoding of custom models is also supported. So you can simply wrap models into a dictionary.
structUser:Codable{letname:String}letuser=User(name:"Stefan")varuserDict=CodableDictionary(value:["user": user])
userDict.additionalEncoding ={(container, codingKey, value)iniflet user = value as?User{try container.encode(user, forKey: codingKey)}}letencodedData:Data=try!JSONEncoder().encode(userDict)letjsonString=String(data: encodedData, encoding:.utf8)Since CodableDictionary has to know the type of model which has to be decoded/encoded, Any has to be one of the following types:
| supported types of Any |
|---|
| String, [String] |
| Bool, [Bool] |
| Int, [Int] |
| Double, [Double] |
| CodableDictionary |
Current Swift compatibility breakdown:
| Swift Version | Framework Version |
|---|---|
| 4.x | 1.x |
Add the following line to your Cartfile.
github "wieweb/CodableDictionary", ~> 1.0
Then run carthage update.
Just drag and drop the CodableDictionary.swift file in the CodableDictionary folder into your project.
- Create something awesome, make the code better, add some functionality, whatever (this is the hardest part).
- Fork it
- Create new branch to make your changes
- Commit all your changes to your branch
- Submit a pull request
Contact me at wielandweb@gmail.com