Why i can't cast a json value string to bool?
like "1" or "0"
var ABool: Bool?
ABool <- map["KEY"]
You can do it!
Example
struct User: Mappable {
var name = ""
var dict = [String:Any]()
var flag = false
init() {}
init?(map: Map) {
}
mutating func mapping(map: Map) {
name <- map["name"]
dict <- map["dict"]
flag <- (map["flag"], TransformOf(fromJSON: { (intVal: Int?) -> Bool? in
return Bool(NSNumber(value: intVal ?? 0))
}, toJSON: { (boolVal: Bool?) -> Int? in
return (boolVal ?? false) ? 1 : 0
}))
}
}
let newJsonString = "{\"dict\":{\"key2\":\"value2\",\"key1\":\"value1\"},\"name\":\"test\",\"flag\":1}"
guard let newU = User(JSONString: newJsonString) else {return}
print(newU)
//// User(name: "test", dict: ["key2": value2, "key1": value1], flag: true)
Thanks @chenkefeng. Thats the correct approach 👍
Most helpful comment
You can do it!
Example