Krutarth Patel Krutarth Patel - 22 days ago 12
iOS Question

Type '(String, AnyObject)' has no subscript members in swift

I am using this line to get data

let productDict = arrProductCart[sender.tag] as! [String: AnyObject]


and I want to filter data from dictionary so i am using this code

let filteredSubitems = productDict.filter{
$0["groupid"] as!String != "1"
}


it is giving me error Type '(String, AnyObject)' has no subscript members

do i need to convert [String: AnyObject] to [String: String]?
what to do.

Answer

Most probably you want to filter arrProductCard array instead of productDict, which doesn't make sense. Try this:

let filteredProducts = arrProductCard.filter{
    guard let groupId = $0["groupid"] as? String else { return false }
    return groupId != "1"
}

You should avoid forced unwrapping whenever you can. Note that your code inside filter closure will crash if there is no groupid value in the dictionary or if it is not a string.

Comments