Reading the Type Casting section of the Swift Guide I see I use the is
keyword to type check variables.
func isString(test: AnyObject?) -> Bool {
return test is String
}
It seems when I try something similar to check for a Tuple containing three NSNumber objects, I receive a 'Tuple does not conform to protocol AnyObject
'. Is there any way to check if a variable contains a Tuple?
func isTuple(test: AnyObject?) -> Bool {
return test is (NSNumber, NSNumber, NSNumber) // error
}
You can't use AnyObject
here because a tuple is not an instance of a class type.
AnyObject
can represent an instance of any class type.Any
can represent an instance of any type at all, including function types.
From The Swift Programming Guide - Type Casting
Instead, try using the more general Any
type:
func isTuple(test: Any?) -> Bool {
return test is (NSNumber, NSNumber, NSNumber)
}
isTuple("test") // false
let tuple: (NSNumber, NSNumber, NSNumber) = (Int(), Int(), Int())
isTuple(tuple) // true