3

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

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Sam
  • 105
  • 1
  • 9
  • `var songDict: Dictionary()` would not compile. it should be either var `songDict: Dictionary` (define the var and its type but no init) or `var songDict = Dictionary()` (define var with type and init) – Scriptable Aug 14 '20 at 08:32
  • 1
    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 Aug 14 '20 at 08:52

1 Answers1

2

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
    }
Jithin
  • 913
  • 5
  • 6