Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift check if value is of type array (of any type)

Tags:

generics

swift

How can I check in Swift if a value is an Array. The problem is that an array of type Int can apparently not be casted to an array of type Any. Suppose I have an array myArray of type Int and execute the following:

if let array = myArray as? [Any] { return true }

it doesn't return true (which surprises me actually). The same thing appears with dictionaries. I want a dictionary of type String, Any (meaning that Any can be any type). How can I check if it is?

Thanks in advance.

like image 413
borchero Avatar asked Nov 20 '25 14:11

borchero


1 Answers

Got it working like this, although it's not as beautiful as I would've hoped:

protocol ArrayType {}
extension Array : ArrayType {}

let intArray : Any = [1, 2, 3]
let stringArray : Any = ["hi", "hello", "world"]

intArray is ArrayType       // true
stringArray is ArrayType    // true

EDIT: I think I misunderstood your question before, now I got it though:

let intArray = [1, 2, 3]

let anyArray = intArray.map{ $0 as Any }

This is the only way to my knowledge.

like image 112
Kametrixom Avatar answered Nov 22 '25 09:11

Kametrixom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!