2
votes

I'm trying to remove "songDict" from "libraryArray" but it triggers an error.

var libraryArray = UserDefaults.standard.value(forKey: "LibraryArray") as! [Dictionary<String, Any>]

var songDict = Dictionary<String, Any>()

var arr = libraryArray.filter {$0 != songDict}

And here's the error. Value of protocol type 'Any' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols

1
var songDict: Dictionary<String, Any>() would not compile. it should be either var songDict: Dictionary<String, Any> (define the var and its type but no init) or var songDict = Dictionary<String, Any>() (define var with type and init) - Scriptable
Unrelated but there is dictionary(forKey in UserDefaults. You should use value(forKey only if you know what KVC is and you really need it. - vadian

1 Answers

2
votes

As the error says, you cannot compare two dictionaries like that as they dont conform to Equatable protocol. It will be better to use a struct for your data model instead of Dictionary.

struct Library: Equatable {
    let id: String
    ...
}

But if you don't want to do that, you can still check for equality with your dictionaries by equating the value of any keys in it.

    var arr = libraryArray.filter { (dict) -> Bool in
        dict["id"] as? String == songDict["id"] as? String
    }