Search code examples
iosswiftnsarraynsdictionary

Turning Dictionary passed into two Arrays


I pass a dictionary of data from the iPhone to WatchKitExtension. What is the best way to turn the received Dictionary into two different item arrays?

iPhone Data:

let applicationDict = [“Item1” : data.item1, “Item2” : data.item2]
let transfer = WCSession.defaultSession().transferUserInfo(applicationDict)

Watch ExtensionDelegate:

var incomingData = Array<Dictionary<String, String>>()

func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
        if let item1Value = userInfo[“Item1”] as? String, let item2Value = userInfo[“Item2”] as? String {
            incomingData.append([“Item1” : item1Value , “Item2” : item2Value])
            // use incomingData to make two item arrays
        } 
}

I've looked at some other questions that seem similar, and it seems like something along the lines of componentArray = Array(incomingData.values) but I can't get that to work.

EXAMPLE:

Item1 is cities. Item2 is states. So the Item1 array would be ["Chicago", "San Francisco"], and the Item2 array would be ["Illinois", "California"].


Solution

  • incomingData is an array of dictionaries. I don't believe this is what you actually want. If you're passing in a city / state pair with each transfer, then this should work in your ExtensionDelegate.

    var cities = [String]()
    var states = [String]()
    
    func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
        if let item1Value = userInfo["Item1"] as? String, let item2Value = userInfo["Item2"] as? String {
            cities.append(item1Value)
            states.append(item2Value)
        }
    }