I'm trying to learn about dictionaries and nsusersdefaults in swift. I wrote a small program that creates a dictionary of strings and uses that dictionary to populate a tableview. Next I save the dictionary to NSUserDefaults. Everything at this point is working great. It's when I attempt to pull the dictionary back out and use it that things go wrong.
Here is my complete code, the error is on the line myDict = userDefaults and the error is Cannot assign a value of type '[String : AnyObject]' to a value of type '[Dictionary]':
import UIKit
// Create dictionary
var myDict = [Dictionary<String,String>()]
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(myDict.count)
// Dictionary starts out with 1 item when new
// so remove that one thing and create it if needed
if myDict.count == 1 {
myDict.removeAtIndex(0)
// Put some stuff in the dictionary
myDict.append(["name":"Bill","age":"39","sex":"male"])
myDict.append(["name":"Nick","age":"8","sex":"male"])
print(myDict)
} else {
if let userDefaults = NSUserDefaults.standardUserDefaults().dictionaryForKey("myDict") {
myDict = userDefaults
}
}
}
override func viewDidAppear(animated: Bool) {
NSUserDefaults.standardUserDefaults().setObject(myDict, forKey: "myDict")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return myDict.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel!.text = myDict[indexPath.row]["name"]
return cell
}
}