简体   繁体   中英

Binary operator '==' cannot be applied to operands of type 'Any?' and 'String' Swift iOS

I have this var json : [[String : Any]] = [[:]] which contains the JSON response as follows:

{
"id": "1",
"name": "Apple",
"category_name": "Fruits"
},
{
"id": "2",
"name": "Black shirt",
"category_name": "Fashion"
},
{
"id": "3",
"name": "iPad",
"category_name": "Gadgets"
}

And I wrote an enum:

enum : Int {
        case fruits = 0, fashion, gadgets
    }

var data = [Categories: [[String: Any]]]()

Then I have this method to sort the categories:

func sortData() {
        data[.fruits] = self.json.filter({ $0["category_name"] == "Fruits" })
        data[.fashion] = self.json.filter({ $0["category_name"] == "Fashion" })
        data[.gadgets] = self.json.filter({ $0["category_name"] == "Gadgets" })
    }

After that I get an error like this

Binary operator ' == ' cannot be applied to operands of type ' Any? ' and ' String '

Please tell me how do I solve that one?

The problem is that you're trying to compare values of differing types, namely Any? and String . To quickly solve the problem you might want to try and convince Swift that your Any? is actually a string value. Try replacing $0["category_name"] with ($0["category_name"] as? String) , which will turn it into String? . Swift will then be able to compare the optional string with your given category string.

您应该安全地将左侧的值强制转换为String ,如下所示:

data[.fruits] = self.json.filter({ ($0["category_name"] as? String) == "Fruits" })

Swift 5

Change following codes from

func sortData() {
        data[.fruits] = self.json.filter({ $0["category_name"] == "Fruits" })
        data[.fashion] = self.json.filter({ $0["category_name"] == "Fashion" })
        data[.gadgets] = self.json.filter({ $0["category_name"] == "Gadgets" })
    }

to

func sortData() {
        data[.fruits] = self.json.filter({ $0["category_name"] as? String  == "Fruits" })
        data[.fashion] = self.json.filter({ $0["category_name"] as? String == "Fashion" })
        data[.gadgets] = self.json.filter({ $0["category_name"] as? String == "Gadgets" })
    }

This will fix the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM