Swift:检查来自对象的属性类型(反射)

时间:2015-05-20 15:07:05

标签: ios swift xcode6

我想在运行时使用反射来检查给定对象的属性类型。

我使用此代码:

//: 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")
}

正如您在此代码中看到的那样,我无法检查“valueType”,因为它是一个可选项。

但是如何检查这个“可选”属性的类型?

谢谢, Urkman

1 个答案:

答案 0 :(得分:4)

请注意,可选的Int是与Int不同的类型,因此您必须使用Int?.Type

进行检查
if reflect(object)[1].1.valueType is Int?.Type {
    println("Int Optional")
}
相关问题