Skip to content

Swift and EasyMapping

DenHeadless edited this page Dec 1, 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 = Person(properties: personInfo)

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.

Clone this wiki locally