Swift 检查对象数组的动态类型

Swift Check Dynamic Type of Array of Objects

我有一个对象数组 array: [AnyObject] 并且想根据类数组检查它们的动态类型我该怎么做?

let array: [AnyObject] = ["hi", true, 12]

上面的数组就是一个例子。我希望它与为数组传递的任何类型一起使用。 我希望有另一个类型数组来检查。但是我不知道怎么申报。

如果您可以将对象限制为 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-仅对象执行此操作。

您可以保留 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