Skip to content

Swift and EasyMapping

Denys Telezhkin edited this page Jul 26, 2014 · 3 revisions

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.

Example

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

Limitations

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.

Known issues

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
Clone this wiki locally