Checking if an object is a given type in Swift

I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances.

How can I check if an object is of a given type in Swift?


Solution 1:

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
}

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
   }
}

Solution 2:

In Swift 2.2 - 5 you can now do:

if object is String
{
}

Then to filter your array:

let filteredArray = originalArray.filter({ $0 is Array })

If you have multiple types to check:

    switch object
    {
    case is String:
        ...

    case is OtherClass:
        ...

    default:
        ...
    }