Swift Reflection映射属性

时间:2016-11-22 03:06:31

标签: swift reflection

在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
    }
}

2 个答案:

答案 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)

Swift 3目前只使用镜像具有相当基本的反射功能 - 如记录here

在您的情况下,您可以将其用作:

let user = User()
user.name = "Michael"
let mirror = Mirror(reflecting: user)
print(mirror)
for case let (label?, value) in mirror.children {
    print ("\(label) \(subjectType) = \(value))
    // ... Prints name String = Michael
}

可以找到一篇好文章here