4

I am having a lot of trouble de-serializing and serializing a nested model in Swift using Mantle. I believe I have everything set up correctly, but I can't even get past the compilation errors. To give some perspective, I have successfully transformed classes that do not have nested model objects. Here's my class:

class TheClass : MTLModel, MTLJSONSerializing
{
    var person:Person?

    static func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]!
    {
        return ["person" : "person"]
    }

    static func personJSONTransformer() -> NSValueTransformer!
    {
        return MTLValueTransformer.reversibleTransformerWithForwardBlock(
        { (person:[NSObject : AnyObject]!) -> AnyObject! in
            do
            {
                return MTLJSONAdapter.modelOfClass(Person.self, fromJSONDictionary: person)
            }
            catch
            {
                return Person()
            }
        },
        reverseBlock:
        { (person:Person) -> AnyObject! in
            return MTLJSONAdapter.JSONDictionaryFromModel(person)
        })
    }
}

This code will not compile, and I can't get it to compile. Here is the error message I am receiving:

Cannot convert return expression of type 'AnyObject!' to expected return type 'Person'

I've tried changing the return type of the reverse block to Person and Person!, but I get the same error message. I've been struggling with this for quite some time and could not find a working example in Swift, so any help would be greatly appreciated.

Alexander
  • 3,959
  • 2
  • 31
  • 58

1 Answers1

5

I found out how to do it! I actually only needed to de-serialize my models to read them from the JSON. Here's how I did it:

class TheClass : MTLModel, MTLJSONSerializing
{
    var person:Person?

    static func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]!
    {
        return ["person" : "person"]
    }

    static func personJSONTransformer() -> NSValueTransformer!
    {
        return MTLJSONAdapter.dictionaryTransformerWithModelClass(Person.self)
    }
}

And if you have an array of nested models:

class TheClass : MTLModel, MTLJSONSerializing
{
    var person:[Person]?

    static func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]!
    {
        return ["person" : "person"]
    }

    static func personJSONTransformer() -> NSValueTransformer!
    {
        return MTLJSONAdapter.arrayTransformerWithModelClass(Person)
    }
}

That's all there is to it!

Alexander
  • 3,959
  • 2
  • 31
  • 58