Type checking and iterating through ANY array in Swift

126 views Asked by At

I'm using reflection to try to make a Swift 2.0 using XCode 7 Beta JSON Serializer. I get a value that is unwrapped into an Any? type. I can check if it's an array by saying:

if value is NSArray { ... }

But that doesn't work for arrays that contains Optionals like

Array<Int?>
Array<Double?> 

Etc... I have two questions:

  1. How can I check type for Array containing any optional type as well?

  2. How can I iterate through such an array no matter what types it contain, be it optionals or non-optionals?

See comments in this gist for context: https://gist.github.com/peheje/d69351ce2181ba349337 Seems to work all-right so far, as long as arrays doesn't contain optionals.

1

There are 1 answers

0
Peheje On

Alright to respond to my own question:

For checking for arrays that contains optional value, I went full verbose. It won't catch arrays filled with optional custom objects. As for casting to an array that can be iterated I used Array constructor with the arrayLiteral argument.

if value is Array<Int?> || value is Array<Double?> || value is Array<Float?> ||
   value is Array<Bool?> || value is Array<String?> {
                let array = Array(arrayLiteral: value)
                for i in array {
                    print(i)
                }
            }

Funnily enough, I still can't unwrap the values with the ! operater. Always turns out as optionals.

As verbose as I could get:

if value is Array<Int?> || value is Array<Double?> ||
            value is Array<Float?> || value is Array<Bool?> || value is Array<String?> {
                let array: Array<Any?>? = Array(arrayLiteral: val)
                for i in array! {
                    print(i!)
                }
        }

Still returns: [Optional(1), nil, Optional(3), Optional(4), Optional(5), Optional(6)] For an:

Array<Int?>

It may be a bug, Swift 2.0 is still in development so yea.

Edit:

Turns out I'm not iterating more than 1 time... can't access each element. I'll leave it at this atm.