How can I check if a variable is an array but not a specific array type in Swift?
The following code works if you import Foundation
func isArray(value: AnyObject) -> Bool {
return value is [AnyObject]
}
However, if you don't import Foundation
, it gives an error because "[AnyObject] does not conform to the AnyObject protocol".
The reason this fast compiler behaves differently when imported Foundation
. Only classes match AnyObject
. Any
protocol for everyone (class, structure, enumeration, etc.). So, without importing, the Foundation
type Array
is the type of the struct and does not conform to the protocol AnyObject
in swift. On import Foundation
, the swift compiler implicitly converts Array
to NSArray
and becomes a class and of course matches AnyObject
. This is why the Foundation
above code works differently when importing .
source to share
You can use the NSObject "isKindOfClass ()" method to check if a variable stores an instance of the class you want to compare:
let isArray: Bool = myVariable.isKindOfClass(NSArray)
// OR
if myVariable.isKindOfClass(NSArray) {
// whatever
}
or
let isArray: Bool = myVariable is NSArray
// OR
if myVariable is NSArray {
// whatever
}
"isKindOfClass ()" only works with classes that are subclasses of NSObject
"is" works with any class in Swift
source to share
It's like checking if it Any.Type
's optional .
With Swift 2, there is no covariance and contravariance in the language . Also, checks for non-printable Arrays
(or any non-trivial general) are still not supported.
As with Any.Type
-is- Optional
, Array
it can be extended to implement a verifiable protocol hidden behind an unsigned array:
protocol ArrayProtocol{}
extension Array: ArrayProtocol {}
["one", "two"] is ArrayProtocol // true
[12, true, "nay"] is ArrayProtocol // true
"not an array" is ArrayProtocol // false
source to share