-
Notifications
You must be signed in to change notification settings - Fork 75
Swift and EasyMapping
Most of functionality of EasyMapping works fine with Swift. Here's Objective-C example from readme, converted to Swift.
You can find all source code, with unit tests, inside EasyMappingSwiftExample directory.
class Person: EKObjectModel {
var name : String!
var email: String!
var car : Car?
var phones: [Phone]!
}
class Car: EKObjectModel {
var model : String!
var year : String!
var createdAt : NSDate!
}
class Phone: EKObjectModel {
var DDI: String?
var DDD: String?
var number: String?
}
Mapping for these classes will look like this:
extension Person {
override class func objectMapping() -> EKObjectMapping{
var mapping = EKObjectMapping(objectClass: self)
mapping.mapPropertiesFromArray(["name","email"])
mapping.hasOne(Car.self, forKeyPath: "car")
mapping.hasMany(Phone.self, forKeyPath: "phones")
return mapping
}
}
extension Car {
override class func objectMapping() -> EKObjectMapping{
var mapping = EKObjectMapping(objectClass: self)
mapping.mapPropertiesFromArray(["model","year"])
return mapping
}
}
extension Phone {
override class func objectMapping() -> EKObjectMapping!
{
var mapping = EKObjectMapping(objectClass: self)
mapping.mapPropertiesFromArray(["number"])
mapping.mapPropertiesFromDictionary(["ddi":"DDI","ddd":"DDD"])
return mapping
}
}
Creating objects is easy as well
let person = EKMapper.objectFromExternalRepresentation(personInfo, withMapping: Person.objectMapping()) as Person
EasyMapping framework is written in Objective-C, and it doesn't have support for Swift-only data structures, like Swift enums and Swift structs.
Any class, that needs to use mapping, has to be enabled for Objective-C runtime. This can be done by using @objc keyword, or directly inheriting from NSObject. Convenience EKObjectModel class can also work as ancestor to mapped classes.
As of XCode beta 4, there's no possibility to create Swift objects using provided by EKObjectModel initWithProperties: method. This is probably a bug, and hopefully will be fixed in future release of Swift.
As a workaround, use EKMapper method
let car = EKMapper.objectFromExternalRepresentation(carInfo, withMapping: Car.objectMapping()) as Car