2015-05-20 35 views
2

我想在運行時使用反射來檢查給定對象的屬性類型。Swift:檢查對象的屬性類型(Reflection)

我用這個代碼:

//: Playground - noun: a place where people can play 
import UIKit 

class Object: NSObject 
{ 
    var type:Int? 
    var name="Apple" 
    var delicious=true 
} 

let object = Object() 

// now check the "type" property 
println(reflect(object)[1].1.value) // this gives me nil 
println(reflect(object)[1].1.valueType) // this gives Swift.Optional<Swift.Int> 

// check for Optional... works fine - Says "Optional" 
if reflect(object)[1].1.disposition == MirrorDisposition.Optional { 
    println("Optional") 
} 

// check for type... does not work, because type is an optional - says: not Int 
if reflect(object)[1].1.valueType is Int.Type { 
    println("Int") 
} else { 
    println("no Int") 
} 

正如你可以在這個代碼中看到的,我can'n檢查「值類型」,因爲它是一個可選項。

但是,如何檢查此「可選」屬性的類型?

感謝, Urkman

+0

檢查您_know_了'type'屬性的類型。它是一個'Int?'。你還需要知道什麼? – matt

+0

因爲這是通用的,所以「對象」只是一個例子。這可能是任何對象... – Urkman

+0

對,但我的意思是,斯威夫特並不真的希望你這樣做。它沒有_real_反射,這是故意的。 – matt

回答

4

注意,可選的詮釋是從int不同類型的,所以你必須與詮釋?。鍵入

if reflect(object)[1].1.valueType is Int?.Type { 
    println("Int Optional") 
} 
+0

就是這樣......謝謝......有時候就是那麼簡單...... – Urkman