Skip to content

Repository files navigation

CodableDictionary

Swift 4Carthage compatible

Struct to make simple [String: Any] dictionaries conform to Codable.

Usage

Decoding

letdata1:Data=try!Data(contentsOf:Bundle.main.url(forResource:"test", withExtension:"json")!)letdict=try?JSONDecoder().decode(CodableDictionary.self, from: data)letname=dict?["name"]

Encoding

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)

Limitations

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

Version Compatibility

Current Swift compatibility breakdown:

Swift VersionFramework Version
4.x1.x

Installation

Carthage

Add the following line to your Cartfile.

github "wieweb/CodableDictionary", ~> 1.0

Then run carthage update.

Manually

Just drag and drop the CodableDictionary.swift file in the CodableDictionary folder into your project.

Contributing

  • 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

Contact me at wielandweb@gmail.com

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages