Search code examples
swiftuitableviewswift3userdefaults

How do I put the complete UserDefaults list into a tableview - Swift 3


I am trying to put the list of UserDefaullts into a UITableView. I just want each key that I have saved to be able to show up in an individual cell. I placed all the individual items in variables so that they can be easily called. Here is one for example:

var A = UserDefaults.standard.string(forKey: "A")

I want to be able to put these in an array, but not every var is going to necessarily be used.

I'm sorry if this does not make much sense, I am not able to explain this very well. If you would like me to clarify anything please let me know!

Thanks


Solution

  • So let say you set your items into UserDefaults like this:

    let array = ["one", "two", "three"]
    let defaults = UserDefaults.standard
    defaults.set(array, forKey: "StringArray")
    

    Then you retrieve the items as an array as the following:

    let defaults = UserDefaults.standard
    let array = defaults.stringArray(forKey: "StringArray") ?? [String]()
    

    Then use the array as your UITableView datasource.

    To get all values/keys from User Defaults:

    Values:

    print(UserDefaults.standard.dictionaryRepresentation().values)
    

    Keys:

    print(UserDefaults.standard.dictionaryRepresentation().keys)