在swift中有什么看起来像java反射,或者我必须像下面的代码一样逐个映射?
class User: Model {
var name: String
override init(data: Dictionary<String, AnyObject>){
super.init(data: data)
self.name = data["name"] as? String
if let vouchers_count = data["vouchers_count"] as? Int {
self.vouchers_count = vouchers_count
}
}
答案 0 :(得分:1)
您可以使用EVReflection等库。
import EVReflection
class User: EVObject {
var name: String = ""
var vouchers_count: Int = 0
}
let alice = User(json: "{\"name\":\"alice\",\"vouchers_count\":1}")
debugPrint(alice)
/*
testUser = {
"name" : "alice",
"vouchers_count" : 1
}
*/
let bob = User(json: "{\"name\":\"bob\"}")
debugPrint(bob)
/*
testUser = {
"name" : "bob",
"vouchers_count" : 0
}
*/
答案 1 :(得分:0)