2016-11-22 145 views
1

在swift中是否有類似java反射的東西,或者我必須總是像下面的代碼一樣映射一個屬性?Swift Reflection映射屬性

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

回答

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 
    } 
*/ 
0

斯威夫特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