dictionary - How to combine two NSDictionary in Swift -
i beginner in swift , trying apprehend notion of dictionaries.
i have 2 nsdictionary both contain same keys, follow:
var currencyname: nsdictionary = [ "cny": "chinese yuan", "pln": "polish zloty" ] var rawrates nsdictionary = [ "cny": "1.34", "pln": "1.456" ]
i trying combine them 1 dictionary such as:
["cny": "chinese yuan","1.34"] ["pln": "polish zloty","1.456"]
i guess first question sort of variable should put output in ? can use nsdictionary ? reading documentation understanding nsdictionaries work pairs of key/values. possible put 2 values inside dictionary ?
my second question how should go combining 2 dictionaries, have tried use code below without success
for (currency, rawrate) in rawrates { (currencyid, name) in currencyname{ if currency == currencyid { rawrates.append(name string) } } }
you can create dictionary of tuples follow:
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)] = [:] 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"
Comments
Post a Comment