Mapper is a simple Swift library to convert JSON to strongly typed
objects. One advantage to Mapper over some other libraries is you can
have immutable properties.
importMapper// Conform to the Mappable protocolstructUser: Mappable {
let id: Stringlet photoURL: URL?// Implement this initializerinit(map: Mapper) throws {
try id = map.from("id")
photoURL = map.optionalFrom("avatar_url")
}
}
// Create a user!let JSON: NSDictionary =...let user = User.from(JSON) // This is a 'User?'
Using with enums:
enumUserType: String{
caseNormal="normal"caseAdmin="admin"
}
structUser: Mappable {
let id: Stringlet type: UserType
init(map: Mapper) throws {
try id = map.from("id")
try type = map.from("user_type")
}
}
Nested Mappable objects:
structUser: Mappable {
let id: Stringlet name: Stringinit(map: Mapper) throws {
try id = map.from("id")
try name = map.from("name")
}
}
structGroup: Mappable {
let id: Stringlet users: [User]
init(map: Mapper) throws {
try id = map.from("id")
users = map.optionalFrom("users") ?? []
}
}
Use Convertible to transparently convert other types from JSON:
extensionCLLocationCoordinate2D: Convertible {
publicstaticfuncfromMap(_value: Any) throws-> CLLocationCoordinate2D {
guardlet location = value as? NSDictionary,
let latitude = location["lat"] as?Double,
let longitude = location["lng"] as?Doubleelse
{
throw MapperError.convertibleError(value: value, type: [String:Double].self)
}
returnCLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
structPlace: Mappable {
let name: Stringlet location: CLLocationCoordinate2D
init(map: Mapper) throws {
try name = map.from("name")
try location = map.from("location")
}
}
let JSON: NSDictionary = [
"name":"Lyft HQ",
"location": [
"lat":37.7603392,
"lng":-122.41267249999999,
],
]
let place = Place.from(JSON)
structUser: Mappable {
let name: Stringlet JSON: AnyObjectinit(map: Mapper) throws {
// Access the 'first' key nested in a 'name' dictionarytry name = map.from("name.first")
// Access the original JSON (maybe for use with a transformation)try JSON = map.from("")
}
}
See the docstrings and tests for more information and examples.
Open Radars
These radars have affected the current implementation of Mapper
rdar://23376350
Protocol extensions with initializers do not work in extensions
rdar://23358609
Protocol extensions with initializers do not play well with classes
rdar://23226135
Can't conform to protocols with similar generic function signatures
rdar://23147654
Generic functions are not differentiated by their ability to throw
rdar://23695200
Using the ?? operator many times is unsustainable.
rdar://23697280
Lazy collection elements can be evaluated multiple times.
rdar://23718307
Non final class with protocol extensions returning Self don't work
License
Mapper is maintained by Lyft and released under
the Apache 2.0 license. See LICENSE for details
请发表评论