Swift报错:Binary operator '=='无法应用于Any与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

