DataConvertible is a support library for converting models to Data.
structModel:Codable,DataConvertible{letstring:Stringletint:Int}letmodel=Model(string:"abc", int:123)letdata:Data=try model.convertToData()letdecoded:Model=tryModel(data: data)letmodel=Model(string:"abc", int:123)try userDefaults.set(model, forKey:"model")letsaved:Model?= userDefaults.value(Model.self, forKey:"model")// e.g. Keychain
structKeychain{ /* implementation */ }extensionKeychain:DataConvertibleStore{publicfunc set(_ value:DataConvertible, forKey key:String)throws{
// store the value
}publicfunc value<T:DataConvertible>(_ type:T.Type=T.self, forKey key:String)->T?{
// get the value by the key
}}extensionYourClass:DataConvertible{init(data:Data)throws{
// initialize form Data
}func convertToData()throws->Data{
// convert to data
}}If your class conforms to Codable, the class can conform to DataConvertible without any additional implementation.
github"tattn/DataConvertible"- Fork it!
- Create your feature branch:
git checkout -b my-new-feature - Commit your changes:
git commit -am 'Add some feature' - Push to the branch:
git push origin my-new-feature - Submit a pull request :D
DataConvertible is released under the MIT license. See LICENSE for details.