Swift 2-检查空数组的类型(自省) [英] Swift 2 - Check Type of empty Array (Introspection)
本文介绍了Swift 2-检查空数组的类型(自省)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在Swift 2中进行自省,在获取数组的特定类型(在此示例中为Array<String>
)时遇到问题.
I'm currently working on introspection in Swift 2 and have Problems getting the specific type for an Array (in this example an Array<String>
).
var prop = obj.valueForKey("strings")!
if prop is Array<String> {
println("true")
}
if prop is Array<Int> {
println("true")
}
输出为:
true
true
应该是
true
false
是否可以找出数组成员的类型?例如,如果我将数组声明为Array<String>
,我想获取String或至少能够检查如果是.
到目前为止, MirrorType 并没有取得任何成功.
Is there a way to find out the type for the members of the Array? For example, if I daclared the Array as Array<String>
I want to get String or at least be able to check if it is.
MirrorType also did not lead to any success on that by now.
推荐答案
有两种方法可以实现所需的目标:
There are 2 ways to achieve what you want:
-
比
-
if prop.dynamicType == Array<Int>.self
(或[Int].self
),因为[Int]()
创建了一个未使用的整数数组"实例. - 通常,当您检查数组是否为特定类型的数组时,您打算使用它
以某种方式(结果,您可能会将数组强制转换为
[Int]
).话虽如此,我建议使用if let arrayOfInts = prop as? Array<Int> {
.使用此构造,您将检查 类型兼容性,并准备以特殊方式处理数组(使用强制转换的arrayOfInts
引用).
if prop.dynamicType == [Int]().dynamicType {
更好的if prop.dynamicType == Array<Int>.self
(or[Int].self
) which is better thanif prop.dynamicType == [Int]().dynamicType {
because[Int]()
creates an unused instance of "array of integers".- Typically, when you check if an array is specific-typed, you plan to use it
in a certain way (as a result, you will likely cast your array to
[Int]
). Having that said, I recommend usingif let arrayOfInts = prop as? Array<Int> {
. Using this construct, you will check for type compatibility and prepare your array to be treated in a special way (using the castedarrayOfInts
reference).
无论如何,由您决定做什么.
Anyway, it's up to you to decide what to do.
这篇关于Swift 2-检查空数组的类型(自省)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文