A.K.Deshmukh
A.K.Deshmukh

Reputation: 3

Cannot subscript a value of type NSDictionary with an index of type String. While converting from Swift 2.3 -> 3.2

I need Help. While conversion from Swift 2.3 -> 3.2 I received below error. I'm not able to resolve this error.

Below is my coding stuff, where I'm facing some issues.

Error :

Cannot subscript a value of type NSDictionary with an index of type String

At this line : if let tempValue:AnyObject = tempDict["value"] {

if (productToReturn.planoRetailPackSize == nil || productToReturn.planoRetailPackSize == "0.0") {
            if let dataToProcess:NSDictionary = dict["data"] as? NSDictionary {
                    if let productDataRecord:NSDictionary = dataToProcess["productDataRecord"] as? NSDictionary{
                        if let module:NSArray = productDataRecord["module"] as? NSArray{
                            for (_,value) in module.enumerated(){
                                if let parentDic:NSDictionary = value as? NSDictionary{
                                    if let cpmChild:NSDictionary = parentDic["cem:canadaExtensionModule"] as? NSDictionary {
                                        if let tempDict:NSDictionary = cpmChild["retailPackSize"] as? NSDictionary {
                                                if let tempValue:AnyObject = tempDict["value"]  { //Error is Here
                                                let myValue: String = String(describing: tempValue)
                                                productToReturn.planoRetailPackSize = myValue
                                    }
                                }//item
                            }
                        }

                        }
                    }
                }
            }
        }

Please help me. I'm very new to iOS. Not able to understand this type of error.

Upvotes: 0

Views: 898

Answers (2)

vadian
vadian

Reputation: 285072

Use native types

if let dataToProcess = dict["data"] as? [String:Any],
    let productDataRecord = dataToProcess["productDataRecord"] as? [String:Any],
    let module = productDataRecord["module"] as? [[String:Any]] {
    for value in module {
        if let cpmChild = value["cem:canadaExtensionModule"] as? [String:Any],
            let tempDict = cpmChild["retailPackSize"] as? [String:Any],
            let myValue = tempDict["value"] as? String {
            productToReturn.planoRetailPackSize = myValue
        }
    }
}

Note : In the for loop myValue will overwrite planoRetailPackSize in each iteration. This is most likely not intended.

Upvotes: 1

Avi
Avi

Reputation: 7552

The best answer is to use native Swift types. The alternative is to cast your subscripts to NSString.

...
if let tempValue:AnyObject = tempDict["value" as NSString]  {
...

Upvotes: 1

Related Questions