iosswiftswift2swift3.2

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.


Solution

  • 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.