Checking if an object is a given type in Swift

ID : 10148

viewed : 22

Tags : swifttype-inferencetypecheckingswift

Top 5 Answer for Checking if an object is a given type in Swift

vote vote

99

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

80

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:         ...     } 
vote vote

72

If you only want to know if an object is a subtype of a given type then there is a simpler approach:

class Shape {} class Circle : Shape {} class Rectangle : Shape {}  func area (shape: Shape) -> Double {   if shape is Circle { ... }   else if shape is Rectangle { ... } } 

“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

In the above the phrase 'of a certain subclass type' is important. The use of is Circle and is Rectangle is accepted by the compiler because that value shape is declared as Shape (a superclass of Circle and Rectangle).

If you are using primitive types, the superclass would be Any. Here is an example:

 21> func test (obj:Any) -> String {  22.     if obj is Int { return "Int" }  23.     else if obj is String { return "String" }  24.     else { return "Any" }  25. }   ...    30> test (1) $R16: String = "Int"  31> test ("abc") $R17: String = "String"  32> test (nil) $R18: String = "Any" 
vote vote

68

I have 2 ways of doing it:

if let thisShape = aShape as? Square  

Or:

aShape.isKindOfClass(Square) 

Here is a detailed example:

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

Edit: 3 now:

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

59

for swift4:

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

Top 3 video Explaining Checking if an object is a given type in Swift

Related QUESTION?