Dimitri T Dimitri T - 2 months ago 16
Swift Question

how to map a sub-class with ObjectMapper

How do I map a subclass with ObjectMapper?
I am using swift 2.2 and Hyphe, following this as an example but it doesn't use subclasses https://bitbucket.org/hyphe/blog-examples/src/59f61b2d8e68c7d3630b40964c4fe3c191d60de6/fetchData/iOS-TechPost1/?at=master
eg my API is pulling the classes 'title' and poster', but for 'poster' I need it to find the sub-class 'src.

My class 'poster' is a sub-class in my array "images". eg the Json I am pulling in is:

"title" : "Election",
"poster" : {
"src" : "https://example.site/image"
"alt" : ""


}

My swift file for the class is:

import Foundation
import RealmSwift
import ObjectMapper
import Foundation
import RealmSwift
import ObjectMapper

protocol Meta {
static func url() -> String
}

class Specimen: Object, Mappable, Meta {
dynamic var title = ""
dynamic var poster = ""

}

//Impl. of Mappable protocol
required convenience init?(_ map: Map) {
self.init()
}

func mapping(map: Map) {

title <- map["title"]
poster <- map["poster"]
}

//Impl. of Meta protocol
static func url() -> String {
return "https://example.site/data"
}
}


I have tried the following options already but they don't work:
poster <- map["poster{src}"]
poster <- map["poster"["src"]]

Would appreciate your help! Any ideas?

Answer

Per my understanding, you are trying to map a nested json object to a property of a Swift object using ObjectMapper. ObjectMapper supports dot notation for this. Please have a look at the documentation here.

In this case, the correct syntax is: poster <- map["poster.src"].