How can I check if a variable is an array but not a specific array type in Swift?

I want to check whether a variable is an array type (may be [Int]

, [UIView]

or [AnyObject]

), and not just a particular type of type[Int]

+3


source to share


5 answers


I don't know if it is reflect

more or less stable than _stdlib_getDemangledTypeName

that, but this is another option:



if reflect(myVariable).disposition == MirrorDisposition.IndexContainer {
    // myVariable is an array
} else {
    // myVariable is something else
}

      

+2


source


Here's a possible test ( v

- variable):

let ok = _stdlib_getDemangledTypeName(v) == "Swift.Array"

      



If ok

- true

, v

is some array.

+1


source


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 .

0


source


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

0


source


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

      

0


source







All Articles