Aviram Netanel
Aviram Netanel

Reputation: 13675

Swift - How to cast Any to Array \ Dictionary?

I'm trying to parse a json which has an array with Strings, Ints and Arrays

So I'm to iterate on the json {["item1", 2, ["subItem1", "subitem2"] ]} members in the array:

func parse(json : [Any])
for item in json{
    if let arr = item as? Array { //
         //do stuff for array
    } 
}

but I'm getting this compile error:

Generic parameter 'Element' could not be inferred in cast to 'Array<_>'

Upvotes: 1

Views: 3177

Answers (2)

Enea Dume
Enea Dume

Reputation: 3232

You receive the error is because in Swift, Array is a generic container that holds values of a specific type. So you can have an Array<Int> that holds integers, or an Array that holds strings. But you can’t have just an Array. The type of the thing the array contains is the generic parameter, and Swift is complaining because it can’t figure out what that type should be. Sometimes it can infer that type from the context of the code around it, but not always, as in this case.

func parse(json : [Any])
for item in json{
    if let arr = item as? Array<Any> { //
         //do stuff for array
    } 
}

Instead of writing Array<Any>, you can write the shorter form, [Any].

You can also solve the problem by using NSArray, as you’ve found. Unlike Array, NSArray doesn’t use generics, since it originates in Objective-C which has a different approach to Swift. Instead, NSArray holds only one kind of thing, an AnyObject. This is is a reference that can point to instances of any class.

Upvotes: 1

vadian
vadian

Reputation: 285260

Optional bind item to the different types

for item in json {
    if let stringItem = item as? String {
         //do stuff for String
    } else if let intItem = item as? Int {
        //do stuff for Int
    } else if let arrayItem = item as? [String] {
       //do stuff for Array
    } else {
       // it's something else
    }
}

Upvotes: 3

Related Questions