Search code examples
iosswiftuserdefaults

Deteting item in an array stored in UserDefaults


I am saving items in UserDefaults and it works fine. I simply append new elements to the array. now deleting the entire saved items is done but now I want to enable the user the ability to delete just one item instead of deleting the entire saved items.

below is how I delete all the entire array

public func deleteSavePropery() {
        delete(key: propertyKey)
    }
    private func delete(key: String) {
        storage.removeObject(forKey: key)
    }

NOTE, saveProperty is a Codable object


Solution

  • You need to retrieve the array if exists then delete the item finally save back

    let storage = UserDefaults.standard
    
    private func deleteItem(key: String,item:Item) {
        if let data =  storage.data(forKey: key) , var arr =  try? JSONDecoder().decode([Item].self, from: data) {
            arr.removeAll(where: { $0 == item})
            guard let res =  try? JSONEncoder().encode(arr) else { return }
            storage.set(res, forKey: key) 
        }
    }
    

    struct Item:Codable,Equatable { 
        let name:String 
    }