Search code examples
iosswiftuserdefaults

Removing a single key value of UserDefaults in Swift 3


I am tracking a user's preferences in my iOS app using UserDefaults -- when a user selects a table cell, it adds the cell's text to my key. That part works.

Now, I want to allow the user to remove the matching key value from the key when a row is selected. If a cell says "Episode 1", it should remove the value from UserDefaults.

From the documentation, there's an instance method for removeObject. Here's what I wrote:

    let defaults = UserDefaults.standard
    var myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
    if let datastring = TableData[indexPath.row] as? String {
        if !myarray.contains(datastring) {
            myarray.append(datastring)
            defaults.removeObject(myarray, forKey: "SavedStringArray")
            defaults.synchronize()
        }

This returns an error for Extra argument in call -- I assume it means myarray, but if I can't add that argument, how can I tell it to remove only one value (stored in myarray)?

If I print the UserDefaults.standard, it will return a list of stored episode values like `["First Episode", "Second Episode", "Third Episode"]

Any idea how I can remove Third Episode when that cell is clicked here?


Solution

  • I have following code which will work for you.

    if myarray.contains(datastring) {
        myarray.remove(at: myarray.index(of: datastring)!)
    } else {
        myarray.append(datastring)
    }
    defaults.set(myarray, forKey: "SavedStringArray")
    

    This code will remove element from array and set array again in User defaults for same key, So it will replace you array with new array.