Qadir Hussain Qadir Hussain - 1 month ago 12
Swift Question

Swift 3 ternary operator Error Type 'Any' has no subscript members

I have a function

func test (food_item_raw:NSArray){

for j in 0...food_item_raw.count-1{

let food_name = food_item_raw[j]["food_name"] as? String == nil ? "nil" : food_item_raw[j]["food_name"] as! String

let food_url = food_item_raw[j]["food_url"] as? String == nil ? "nil" : food_item_raw[j]["food_url"] as! String

let food_price = food_item_raw[j]["food_price"] as? String == nil ? "nil" : food_item_raw[j]["food_price"] as! String

let food_desc = food_item_raw[j]["food_desc"] as? String == nil ? "nil" : food_item_raw[j]["food_desc"] as! String

//let food_item = FoodItems(food_url: food_url, food_name: food_name, food_catagory: food_type,food_price: food_price, food_desc: food_desc)

//weakFoodArray.append(food_item)

}
}


this was working fine in swift 2 and swift 2.3 but in swift 3 I am getting error
Type 'Any' has no subscript members


here is screenshot

code screen shot

Answer

Why it happens?

NSArray in Swift 3 is bridged to [Any]. So food_item_raw[j] has type Any.

And here's your Error Type 'Any' has no subscript members. Any is empty protocol, it has nothing, not even subscript.

Solution

To prevent this just add some types, change NSArray to [T], where T is the Type, it your case it looks like T == [String: String]. It will save you from type casting in every line too.

You can change your code to this, for example:

func test (food_item_raw:[[String: String]]) {

    for food_item in food_item_raw {

        let food_name = food_item["food_name"] ?? "nil"

        let food_url = food_item["food_url"] ?? "nil"

        let food_price = food_item["food_price"] ?? "nil"

        let food_desc = food_item["food_desc"] ?? "nil"

        //let food_item = FoodItems(food_url: food_url, food_name: food_name, food_catagory: food_type,food_price: food_price, food_desc: food_desc)

        //weakFoodArray.append(food_item)

    }
}

And, btw, i replaced for by index with enumerating for, because food_item_raw[j] in every line is redundant and looks silly.

Also that huge overcomplicated ternary operator can be replaced with Nil-Coalescing Operator(??), which does same thing, but is way shorter.

Comments