How to combine two NSDictionary in Swift

I am starting quickly, and I am trying to understand the concept of dictionaries.

I have two NSDictionary that contain the same keys:

var currencyname: NSDictionary = [
        "CNY": "Chinese Yuan",
        "PLN": "Polish Zloty"
]

var rawrates NSDictionary = [
        "CNY": "1.34",
        "PLN": "1.456"
]

I try to combine them to get only one dictionary, for example:

        ["CNY": "Chinese Yuan","1.34"]
        ["PLN": "Polish Zloty","1.456"]

I guess my first question is, which variable should I put the output? Can i use NSDictionary? Due to the fact that I was reading the documentation, I realized that NSDictionaries work on Key / Values ​​pairs. Can I put two words in a dictionary?

My second question: how should I combine these two dictionaries, I tried to use the code below without much success

for (currency, rawrate) in rawrates {
                for (currencyid, name) in currencyname{
                    if currency == currencyid {
                        rawrates.append(name as String)
                    }
                } 
}
+4
source share
3 answers

You can create a tuple dictionary as follows:

let currencyname:[String:String] = ["CNY": "Chinese Yuan", "PLN": "Polish Zloty"]
let rawrates:[String:String] = ["CNY": "1.34", "PLN": "1.456"]

var combinedDictionary:[String:(name:String,rate:String)] = [:]


for key in currencyname.keys.array {
    combinedDictionary[key] = (currencyname[key]!,rawrates[key]!)
}


// Testing

combinedDictionary["PLN"]!       // (.0 "Polish Zloty", .1 "1.456")
combinedDictionary["PLN"]!.name  // "Polish Zloty"
combinedDictionary["PLN"]!.rate  // "1.456"

combinedDictionary["CNY"]!       // (.0 "Chinese Yuan", .1 "1.34")
combinedDictionary["CNY"]!.name  // "Chinese Yuan"
combinedDictionary["CNY"]!.rate  // "1.34"
+2
source

. , .

, , :

[
    "CNY" : ["Chinese Yuan","1.34"],
    "PLN" : ["Polish Zloty","1.456"]
]

, "CNY" "PLN", .

:

var combinedDict = [String:Array<Any>]()
for key in currencyName.allKeys {
    combinedDict[key] = [currencyName[key], rawRates[key]]
}
println(combinedDict)

, , , , - , , -, .

struct Currency {
    let name: String?
    let rawRate: String?
}

:

var currencyInformation = [String:Currency]()
for key in currencyName.allKeys {
    combinedDict[key] = Currency(name: currencyName[key], rawRate: rawRates[key])
}
+1

Another simple answer using string interpolation and safe type:

var currencyName = ["CNY":"Chinese Yuan", "PLN": "Polish Zloty"]
var rawRates = ["CNY":"1.34" , "PLN":"1.456"]
var combined = [String:String]()

for (ccyCode, ccyName) in currencyName
{
    if let possibleRate = rawRates[ccyCode]
    {
        combined[ccyCode] = "\(ccyName), \(possibleRate)"
    }
    else
    {
        combined[ccyCode] = "\(ccyName), N/A"
    }     
}
0
source

All Articles