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"