我有一个对象数组array: [AnyObject]
,想要根据类数组检查它们的动态类型我该怎么做?
let array: [AnyObject] = ["hi", true, 12]
以上数组就是一个例子。我希望它适用于为数组传递的任何类型。 我希望有另一个类型的数组来检查。但我不知道如何宣布它们。
答案 0 :(得分:4)
您可以保留Any
个实例,并将Any.Type
类型与==
运算符进行比较。示例基于@lassej中的代码回答:
let array: [Any] = [UIView(), "hellow", 12, true]
let types: [(Any.Type, String)] = [
(UIView.self, "UIView"),
(String.self, "String"),
(Int.self, "Integer")
]
anyLoop: for any in array {
for (type, name) in types {
if any.dynamicType == type {
print( "type: \(name)")
continue anyLoop
}
}
print( "unknown type: \(any.dynamicType)")
}
// Prints:
// type: UIView
// type: String
// type: Integer
// unknown type: Bool
答案 1 :(得分:1)
如果你可以将对象限制为NSObject的子类,那么这应该有效:
import Foundation
let array: [AnyObject] = ["hi", true, 12]
let types: [(AnyClass, String)] = [
(NSString.self, "String"),
(NSNumber.self, "Number"),
]
for obj in array {
for (type, name) in types {
if obj.isKindOfClass( type) {
println( "type: \(name)")
}
}
}
不确定是否有办法使用Swift-Only对象执行此操作。