Sathish Kumar
Sathish Kumar

Reputation: 87

how to compare String and any type whether it is equal or not in swift?

For example,
let a: String = "sat" let b: Any = "sat"

if a == b

I tried that before.But it shows mismatching type string and any.
Please help me for this problem.I am new to swift.

Upvotes: 1

Views: 910

Answers (3)

Jagdeep
Jagdeep

Reputation: 1178

What is different is var a is String and var b is of Any(anyObject) so you can keep them equalivent. So workaround is change var b to String type before comparing or at comparing

If a == (b as! String){    }

Or

If a == "/(b)"{    }

Upvotes: 2

user3182143
user3182143

Reputation: 9589

If you face that error,First check what type of data it is.

let b: Any = "sat"
print(type(of: b))

It shows me String

enter image description here

Now we can check that by below

If we type cast b with string, the issue has gone.

if a == b as! String {
  ......        
}

Upvotes: 1

Manikandan D
Manikandan D

Reputation: 1442

try below

if(a == "\(b)") // b automatically converted into 'Any' to 'String'
{
   ...
   ...
   ...
}

Upvotes: 2

Related Questions