ggirao ggirao - 2 months ago 15
Swift Question

create and iterate trough an array of arrays of dictionaries

I have successfully created an array of dictionaries that I thought was a final solution for my question (here: Store CLLocation Manager Values in Device swift) and here is the code I came up with:

func arrayOfDictionaries() {
var offline:[[String:AnyObject]] = []
offline.append(["LATITUDE: ": userLocation.coordinate.latitude, "LONGITUDE: ": userLocation.coordinate.longitude, "SPEED: ": userLocation.speed])

NSUserDefaults().setObject(offline, forKey: "offLine")

if let offLinePositions = NSUserDefaults().arrayForKey("offLine") as? [[String:AnyObject]] {
//print(offLinePositions)


for item in offLinePositions {
print(item["LATITUDE: "]! as! NSNumber) // A, B
print(item["LONGITUDE: "]! as! NSNumber) // 19.99, 4.99
print(item["SPEED: "]! as! NSNumber) // 1, 2
}
}

}


But when I tested the app, I realized that I only have 1 position stored in the array. So my thought is to create another array and insert the values from the first one. How can I do that?

Answer

You're creating offline array, appending one item to it and then overwriting the offLine array in the user defaults with this . That's why you only have one item in it.

First you need to try to grab the existing array from the user defaults then append another item to it and write it back to the user defaults:

func arrayOfDictionaries() {
    let defaults = NSUserDefaults.standardUserDefaults()
    var offline:[[String:AnyObject]]
    if defaults.arrayForKey("offLine") != nil {
        //Grab offLine array from user defaults
        offline = defaults.arrayForKey("offLine") as! [[String:AnyObject]]
    } else {
        //Setting the offLine array for the first time
        offline = []
    }
    offline.append(["LATITUDE: ": userLocation.coordinate.latitude, "LONGITUDE: ": userLocation.coordinate.longitude, "SPEED: ": userLocation.speed])

    defaults.setObject(offline, forKey: "offLine")

    if let offLinePositions = NSUserDefaults().arrayForKey("offLine") as? [[String:AnyObject]] {
        //print(offLinePositions)


        for item in offLinePositions {
            print(item["LATITUDE: "]! as! NSNumber)  // A, B
            print(item["LONGITUDE: "]! as! NSNumber)  // 19.99, 4.99
            print(item["SPEED: "]! as! NSNumber)  // 1, 2
        }
    }

}