You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift报错:Binary operator '=='无法应用于Any与Int类型操作数,求解决方案

Fixing "Binary operator '==' cannot be applied to operands of type 'Any' and 'Int'"

Hey there! Let's break down what's causing this error and how to fix it quickly.

The core issue here is that your class_User.day array is typed as [Any] (since it's pulled directly from an API response). Swift is a strongly typed language, so it won't let you compare an Any value directly to an Int or String—it needs to know exactly what type it's working with first.

Solution 1: Safely cast elements to specific types first

Since you're checking for values like 1 (Int) and "2" (String), we can add safe type casts to ensure we're comparing like types. Here's how to adjust your code:

for item in class_User.day {
    // Handle Int values
    if let i = item as? Int {
        if i == 1 {
            print(i)
            strdays += "1"
        } else if i == 2 {
            print(i)
            strdays += "- 2"
        }
    }
    // Handle String values (in case the API returns numbers as strings)
    else if let str = item as? String {
        if str == "1" {
            print(str)
            strdays += "1"
        } else if str == "2" {
            print(str)
            strdays += "- 2"
        }
    }
    // Optional: Catch unexpected types to avoid silent failures
    else {
        print("Skipping unsupported item type: \(type(of: item))")
    }
}

Solution 2: Use a switch statement for cleaner type checking

If your API returns a mix of types and you want more readable code, a switch statement works great:

for item in class_User.day {
    switch item {
    case let i as Int where i == 1:
        print(i)
        strdays += "1"
    case let str as String where str == "2":
        print(str)
        strdays += "- 2"
    default:
        // Handle other values or unrecognized types here
        print("Unrecognized item: \(item)")
    }
}

Pro Tip: Fix the root cause at parsing time

The best long-term fix is to avoid having an [Any] array entirely. When you parse the API response (using Codable, for example), define your class_User model with a specific type for the day property:

If the API returns an array of integers:

class class_User: Codable {
    let day: [Int]
    // Add other properties here...
}

If it returns an array of strings:

class class_User: Codable {
    let day: [String]
    // Add other properties here...
}

This way, you won't have to deal with type casting later on!

内容的提问来源于stack exchange,提问作者Vishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:21:27