Checking if an object is a given type in Swift
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:
...
}
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
}
}