SWIFT – Using the Alamofire and ObjectMapper, the integer value is always zero

I am using Alamofire and ObjectMapper, my model class is like this

class Category: Object, Mappable {

dynamic var id: Int = 0
dynamic var name = ""
dynamic var thumbnail = ""
var children = List()


override static func primaryKey() -> String? {
return "id"
}


required convenience init?(_ map: Map) {
self.init()
}

func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
thumbnail <- map["thumbnail"]
children <- map["children"]
}

}

And I am using Alamofire like this

Alamofire.request(.GET, url).responseArray {(response: Response<[Category], NSError >) in

let categories = response.result.value

if let categories = categories {
for category in categories {
print(category. id)
print(category.name)
}
}
}

The id is always zero, I don’t know why?

I fixed it by adding transformations in the mapping function in the model class

id <- (map["id"], TransformOf(fromJSON: {Int($0!) }, toJSON: {$0.map {String($0 )} }))

Thanks to @BobWakefield

I am using Alamofire and ObjectMapper, my model class is like this

class Category: Object, Mappable {

dynamic var id: Int = 0
dynamic var name = ""
dynamic var thumbnail = ""
var children = List()


override static func primaryKey() -> String? {
return "id"
}


required convenience init?(_ map: Map) {
self.init()
}

func mapping(map : Map) {
id <- map["id"]
name <- map["name"]
thumbnail <- map["thumbnail"]
children <- map["children"]
}

}

And I am using Alamofire like this

Alamofire.request (.GET, url).responseArray {(response: Response<[Category], NSError>) in

let categories = response.result.value

if let categories = categories {
for category in categories {
print(category.id)
print(category.name )
}
}
}

The id is always zero, I don’t know why?

I fixed it by adding transformations in the mapping function in the model class

 id <- (map["id"], TransformOf(fromJSON: {Int($0!) }, toJSON: {$0.map {String($0)} }))

Thanks @BobWakefield

Leave a Comment

Your email address will not be published.