我有一个由组成的数组AnyObject
。我想遍历它,并找到所有属于数组实例的元素。
如何在Swift中检查对象是否为给定类型?
如果要检查特定类型,可以执行以下操作:
if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}
您可以使用“ as!” 如果obj
类型不正确,则会引发运行时错误[String]
let stringArray = obj as! [String]
您也可以一次检查一个元素:
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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句