0

While converting from Swift 2.3 to 3.2 I received below error.

Error : Binary operator cannot be applied to operands of type Int and String

for this if Condition i.e if (error?.code)! == "-112" which is shown in below line.

if (error?.code)! == "-112" 
{
     print("hello")
}
Luuklag
  • 3,897
  • 11
  • 38
  • 57
A.R
  • 3
  • 1
  • 4

3 Answers3

1

Error itself says it's different types Int and String.

You can need to typecast one or another in same form and them compare.

if (String(error?.code)!) == "-112"){
  print("hello")
} 
rohitanand
  • 710
  • 1
  • 4
  • 26
1

Swift is a language with a strong type system. You can compare only values of the same type.

Since the left side is Int anyway use an Int value for the right side. Creating a string is unnecessarily expensive. Don’t do that.

The most efficient (and safe) solution is

if error?.code == -112 
{
     print("hello")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

You need to type-cast your error code result to a string, like so:

if String(error?.code)!) == "-112" {
print("Hello")
}

Essentially, you are taking the error?.code, "casting" it as a string by placing it in a string "container mould" and unwrapping the value (retrieving the casted result).

In addition, if you are working with an API response, you have to account for all other error codes in the else/if statement to make sure all responses are handled properly (just in case you are).

jcdr04
  • 90
  • 1
  • 8