簡體   English   中英

Swift:檢查對象的屬性類型(反射)

[英]Swift: check type of property from object (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")
}

如您在此代碼上看到的,我無法檢查“ valueType”,因為它是可選的。

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

謝謝,烏克曼

請注意,可選的Int是與Int不同的類型,因此必須使用Int?.Type進行檢查。

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

暫無
暫無

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

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