Search code examples
iosswiftuserdefaults

Value of protocol type 'Any' cannot conform to 'Equatable' Swift


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


Solution

  • 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
        }