sl0anage
sl0anage

Reputation: 97

Create an Array of Object from an Array of Dictionaries with Swift

I'm receiving a JSON dictionary from a web service and I need to map the return values to existing values. Here's essentially what I'm trying to do:

class Contract {
var contractID: String?

var ebState: String?
var ibState: String?
var importerState: String?

var exportersBankRefNo: String?
var importersBankRefNo: String?
}

let contract1 = Contract()
contract1.contractID = "001"

let contract2 = Contract()
contract2.contractID = "002"

// This is the JSON return dictionary
let exportAppnStatusList: [[String: String]] = [["contractID":"001",
    "ExporterBankRefNo":"ExporterBankRefNo001",
    "ExporterBankState":"ACCEPTED",
    "ImporterBankRefNo":"",
    "ImporterBankState":"UNKNOWN",
    "ImporterState":"UNKNOWN" ],
  ["contractID":"002",
    "ExporterBankRefNo":"ExporterBankRefNo002",
    "ExporterBankState":"ACCEPTED",
    "ImporterBankRefNo":"ImporterBankRefNo002",
    "ImporterBankState":"ACCEPTED",
    "ImporterState":"UNKNOWN" ]]

I need to take the exportAppnStatusList and fill in the associated values in the existing contract1 and contract2, mapping by the contractID

Upvotes: 3

Views: 666

Answers (3)

binchik
binchik

Reputation: 919

Try using this init (your class must inherit from NSObject):

init(jsonDict: [String: String]) {
        super.init()

        for (key, value) in jsonDict {
        if class_respondsToSelector(Contract.self, NSSelectorFromString(key)) {
            setValue(value, forKey: key)
        }
    }
    }

Then you can do this:

exportAppnStatusList.forEach {
    print(Contract(jsonDict: $0))
}

Upvotes: 0

Sam Clewlow
Sam Clewlow

Reputation: 4351

Why not generate the contract object by mapping over the array of dictionaries like this? You'll need to write a custom initializer that takes all these params

exportAppnStatusList.map { (dict:[Stirng:String]) -> Contract in 
    return Contract(contractID:dict["contractID"],
                    ebState:dict["ExporterBankState"],
                    ibState:dict["ImporterBankState"],      
                    importerState:dict["ImporterState"], 
                    exportersBankRefNo:dict["ExporterBankRefNo"], 
                    importersBankRefNo:dict["ImporterBankRefNo"] 
}

Upvotes: 0

Daniel Klöck
Daniel Klöck

Reputation: 21137

This fills the contracts with available information, it ignores contracts where the id could not be found:

for contract in [contract1, contract2] {
    if let contractDict = exportAppnStatusList.filter({$0["contractID"] == contract.contractID}).first {
        contract.exportersBankRefNo = contractDict["ExporterBankRefNo"]
        contract.ebState = contractDict["ExporterBankState"]
        contract.importersBankRefNo = contractDict["ImporterBankRefNo"]
        contract.ibState = contractDict["ImporterBankState"]
        contract.importerState = contractDict["ImporterState"]
    }
}

Upvotes: 3

Related Questions