簡體   English   中英

如何在swift(Reflection / Mirror)中動態查找屬性的類型?

[英]How can I find the type of a property dynamically in swift (Reflection/Mirror)?

所以,假設我有一個這樣的類:

class Employee: NSObject {
    var id: String?
    var someArray: [Employee]?
}

我使用反射來獲取屬性名稱:

let employee = Employee()
let mirror = Mirror(reflecting: employee)
propertyNames = mirror.children.flatMap { $0.label } 
// ["businessUnitId", "someArray"]

到現在為止還挺好! 現在我需要能夠找出每個屬性的類型,所以如果我執行employee.valueForKey("someArray") ,它將無法工作,因為它只給我AnyObject類型。 最好的方法是什么? 特別是對於數組,我需要能夠動態地告訴該數組包含Employee類型。

您不需要繼承NSObject (除非您有充分的理由)。

class Employee {
    var id: String?
    var someArray: [Employee]?
}

let employee = Employee()

for property in Mirror(reflecting: employee).children {
    print("name: \(property.label) type: \(type(of: property.value))")
}

產量

name: Optional("id") type: Optional<String>
name: Optional("someArray") type: Optional<Array<Employee>>

這也適用於Structs

employee.valueForKey("someArray")!.dynamicType

如果您繼承自NSObject ,則可以使用NSCoding和Objective-C運行時提供的一些方法:

let employee = Employee()
employee.someArray = []
employee.valueForKey("someArray")?.classForCoder // NSArray.Type
employee.valueForKey("someArray")?.classForKeyedArchiver // NSArray.Type
employee.valueForKey("someArray")?.superclass // _SwiftNativeNSArrayWithContiguousStorage.Type

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM