github"tattn/MoreCodable"pod'MoreCodable'structUser:Codable{letid:Intletname:String}letencoder=DictionaryEncoder()letuser=User(id:123, name:"tattn")letdictionary:[String:Any]=try! encoder.encode(user) // => {"id": 123, "name": "tattn"}letdecoder=DictionaryDecoder()letuser=try decoder.decode(User.self, from: dictionary)structParameter:Codable{letquery:Stringletoffset:Intletlimit:Int}letparameter=Parameter(query:"ねこ", offset:10, limit:20)letencoder=URLQueryItemsEncoder()letparams:[URLQueryItem]=try! encoder.encode(parameter)varcomponents=URLComponents(string:"https://example.com")
components?.queryItems = params
components?.url // https://example.com?query=%E3%81%AD%E3%81%93&offset=10&limit=20letdecoder=URLQueryItemsDecoder()letparameter=try decoder.decode(Parameter.self, from: params)structAPIResponse:Encodable{letid:Intlettitle:Stringletfoo:String}structAPIResponse2:Encodable{lettags:[String]}structModel:Decodable{letid:Intlettitle:Stringlettags:[String]}letresponse=APIResponse(id:0, title:"Awesome article", foo:"bar")letresponse2=APIResponse2(tags:["swift","ios","macos"])letmodel=tryObjectMerger().merge(Model.self, response, response2)
// success
XCTAssertEqual(model.id, response.id)XCTAssertEqual(model.title, response.title)XCTAssertEqual(model.tags, response2.tags)structUser:Codable{letuserId:Stringletname:StringenumCodingKeys:String,RuleBasedCodingKey{case userId
case name
func codingKeyRule(key:String)->String{return key.uppercased() // custom rule
}}}letjson="""{"USERID": "abc", "NAME": "tattn"}""".data(using:.utf8)!
letuser=try!JSONDecoder().decode(User.self, from: json) // => User(userId: "abc", name: "tattn")structUser:Codable{letuserId:Stringletname:StringenumCodingKeys:String,SnakeCaseCodingKey{case userId
case name
}}letjson="""{"user_id": "abc", "name": "tattn"}""".data(using:.utf8)!
letuser=try!JSONDecoder().decode(User.self, from: json) // okstructUser:Codable{letuserId:Stringletname:StringenumCodingKeys:String,UpperCamelCaseCodingKey{case userId
case name
}}letjson="""{"UserId": "abc", "Name": "tattn"}""".data(using:.utf8)!
letuser=try!JSONDecoder().decode(User.self, from: json) // okletjson="""[ {"name": "Taro", "age": 20}, {"name": "Hanako"}]""".data(using:.utf8)! // Hanako has no "age"
structUser:Codable{letname:Stringletage:Int}letusers=try!JSONDecoder().decode([Failable<User>].self,
from: json)
// success
XCTAssertEqual(users[0].value?.name,"Taro")XCTAssertEqual(users[0].value?.age,20)XCTAssertNil(users[1].value)letjson="""{"int": "100","articleId": "abc"}""".data(using:.utf8)!
structRoot:Codable{letint:StringTo<Int>letarticleId:StringTo<ArticleId>structArticleId:LosslessStringConvertible,Codable{vardescription:Stringinit?(_ description:String){self.description = description
}}}letroot=try!JSONDecoder().decode(Root.self, from: json)
// success
XCTAssertEqual(root.int.value,100)XCTAssertEqual(root.articleId.value.description,"abc")letjson="""{"date": "2019.05.27","dateTime": "2019-05-27T17:26:59+0000","timestamp": 1558978068,"timestampMilliseconds": 1558978141863,"custom": "1558978068"}""".data(using:.utf8)!
structDocument:Codable{vardate:DatevardateTime:Datevartimestamp:DatevartimestampMilliseconds:Datevarcustom:Date}extensionDocument:MultiDateFormat{staticvardateFormatter:DateFormatter={letformatter=DateFormatter()
formatter.timeZone =TimeZone(identifier:"UTC")
formatter.dateFormat ="yyyy.MM.dd"return formatter
}()staticfunc dateFormat(for codingKey:CodingKey)->DateFormat?{switch codingKey {caseCodingKeys.date:return.formatted(dateFormatter)caseCodingKeys.dateTime:return.iso8601
caseCodingKeys.timestamp:return.secondsSince1970
caseCodingKeys.timestampMilliseconds:return.millisecondsSince1970
caseCodingKeys.custom:return.custom({(date, encoder)invarcontainer= encoder.singleValueContainer()try container.encode(String(date.timeIntervalSince1970))},{(decoder)->Dateinletcontainer=try decoder.singleValueContainer()letstring=try container.decode(String.self)lettimeInterval=TimeInterval(string)!
returnDate(timeIntervalSince1970: timeInterval)})default:returnnil}}}letdecoded=try!MoreJSONDecoder().decode(Document.self, from: json)letencoded=try!MoreJSONEncoder().encode(document)structUser:Codable,Hashable{ // conform to Hashable
letid:Intletname:String}letencoder=DictionaryCachableEncoder()letuser=User(id:123, name:"tattn")letdictionary:[String:Any]=try! encoder.encode(user) // => {"id": 123, "name": "tattn"}
try! encoder.encode(user) // use the previous encoded result for the second time - XMLDecoder/XMLEncoder
- CSVDecoder/CSVEncoder
DataConvertible
https://github.com/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
Donating to help me continue working on this project.
MoreCodable is released under the MIT license. See LICENSE for details.