我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。

我怎么能检查如果一个对象是一个给定的类型在Swift?


当前回答

swift4:

if obj is MyClass{
    // then object type is MyClass Type
}

其他回答

为什么不使用专门为此任务构建的内置功能呢?

let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)

Result: "Array<Any>"

我有两种方法:

if let thisShape = aShape as? Square 

Or:

aShape.isKindOfClass(Square)

下面是一个详细的例子:

class Shape { }
class Square: Shape { } 
class Circle: Shape { }

var aShape = Shape()
aShape = Square()

if let thisShape = aShape as? Square {
    println("Its a square")
} else {
    println("Its not a square")
}

if aShape.isKindOfClass(Square) {
    println("Its a square")
} else {
    println("Its not a square")
}

编辑:3现在:

let myShape = Shape()
if myShape is Shape {
    print("yes it is")
}

Swift 4.2,在我的情况下,使用isKind函数。

isKind (:) 返回一个布尔值,该值指示接收者是给定类的实例还是从该类继承的任何类的实例。

  let items : [AnyObject] = ["A", "B" , ... ]
  for obj in items {
    if(obj.isKind(of: NSString.self)){
      print("String")
    }
  }

阅读更多 https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418511-iskind

Swift 5.2 & Xcode版本:11.3.1(11C504)

以下是我检查数据类型的解决方案:

 if let typeCheck = myResult as? [String : Any] {
        print("It's Dictionary.")
    } else { 
        print("It's not Dictionary.") 
    }

我希望它能帮助你。

只是为了完整起见,基于公认的答案和其他一些答案:

let items : [Any] = ["Hello", "World", 1]

for obj in items where obj is String {
   // obj is a String. Do something with str
}

但是你也可以(compactMap也“映射”过滤器没有的值):

items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }

以及一个使用switch的版本:

for obj in items {
    switch (obj) {
        case is Int:
           // it's an integer
        case let stringObj as String:
           // you can do something with stringObj which is a String
        default:
           print("\(type(of: obj))") // get the type
    }
}

但回到问题上来,检查它是否是一个数组(即[String]):

let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]

for obj in items {
  if let stringArray = obj as? [String] {
    print("\(stringArray)")
  }
}

或者更一般地说(见另一个问题的答案):

for obj in items {
  if obj is [Any] {
    print("is [Any]")
  }

  if obj is [AnyObject] {
    print("is [AnyObject]")
  }

  if obj is NSArray {
    print("is NSArray")
  }
}