Saturday, September 05, 2015

Tip - Swift 2.0 - Converting Keys and Values in a Dictionary into Arrays

Very often, you need to extract keys and values stored within a dictionary as arrays. Here's how to do it:

//---declare a dictionary---
var stocks = Dictionary<String, Double>()

//---populate the dictionary---
stocks["AAPL"] = 109.15
stocks["MSFT"] = 42.97
stocks["GOOG"] = 603.00

//---extract the keys as an array---
let symbols = Array(stocks.keys) //["AAPL", "GOOG", "MSFT"]

//---extract the values as an array---
let prices = Array(stocks.values) //[109.15, 603, 42.97]

No comments: