如何检查 var 是否是 Swift 中的元组?
How do I check if a var is a Tuple in Swift?
阅读 Swift Guide 的类型转换部分,我看到我使用 is
关键字来类型检查变量。
func isString(test: AnyObject?) -> Bool {
return test is String
}
似乎当我尝试类似的方法来检查包含三个 NSNumber 对象的元组时,我收到了 'Tuple does not conform to protocol AnyObject
'。有什么方法可以检查变量是否包含元组?
func isTuple(test: AnyObject?) -> Bool {
return test is (NSNumber, NSNumber, NSNumber) // error
}
你可以这样做:
func isTuple(test: Any?) -> Bool{
return test is (NSNumber, NSNumber, NSNumber)
}
您不能使用 AnyObject
here because a tuple 不是 class 类型的实例。
AnyObject
can represent an instance of any class type.
Any
can represent an instance of any type at all, including function types.
来自The Swift Programming Guide - Type Casting
相反,请尝试使用更通用的 Any
类型:
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
阅读 Swift Guide 的类型转换部分,我看到我使用 is
关键字来类型检查变量。
func isString(test: AnyObject?) -> Bool {
return test is String
}
似乎当我尝试类似的方法来检查包含三个 NSNumber 对象的元组时,我收到了 'Tuple does not conform to protocol AnyObject
'。有什么方法可以检查变量是否包含元组?
func isTuple(test: AnyObject?) -> Bool {
return test is (NSNumber, NSNumber, NSNumber) // error
}
你可以这样做:
func isTuple(test: Any?) -> Bool{
return test is (NSNumber, NSNumber, NSNumber)
}
您不能使用 AnyObject
here because a tuple 不是 class 类型的实例。
AnyObject
can represent an instance of any class type.Any
can represent an instance of any type at all, including function types.
来自The Swift Programming Guide - Type Casting
相反,请尝试使用更通用的 Any
类型:
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