检查对象是否是 Swift 中的给定类型 [英] Checking if an object is a given type in Swift
本文介绍了检查对象是否是 Swift 中的给定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由 AnyObject
组成的数组.我想迭代它,并找到所有是数组实例的元素.
I have an array that is made up of AnyObject
. I want to iterate over it, and find all elements that are array instances.
如何在 Swift 中检查对象是否属于给定类型?
How can I check if an object is of a given type in Swift?
推荐答案
如果要检查特定类型,可以执行以下操作:
If you want to check against a specific type you can do the following:
if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}
您可以使用作为!"如果 obj
不是 [String]
You can use "as!" and that will throw a runtime error if obj
is not of type [String]
let stringArray = obj as! [String]
您也可以一次检查一个元素:
You can also check one element at a time:
let items : [Any] = ["Hello", "World"]
for obj in items {
if let str = obj as? String {
// obj is a String. Do something with str
}
else {
// obj is not a String
}
}
这篇关于检查对象是否是 Swift 中的给定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文