Nachot93
Nachot93

Reputation: 63

Can't convert view.tag ObjC code to Swift

I'm migrating some code to Swift and I stumbled upon this line that for some reason works with ObjC but not with Swift.

ObjC:

if (view.tag == 'C'+'L'+'O') {

And now what I wrote in Swift that isn't working:

if view.tag == "C" + "L" + "O" {

It says Ambiguous reference to operator function '=='

Why is this? How can I fix it?

Upvotes: 0

Views: 66

Answers (2)

EmilioPelaez
EmilioPelaez

Reputation: 19892

In C and ObjC characters (denoted with a single ' quote, instead of double " quotes for strings) are actually ints, which is why you can add them together and assign them to tag, which is an int.

Swift does have a character type, but it's not an int, and in this case you are adding three strings, which will result in the string "CLO", which can't be assigned to the tag property because the property is an int.

Personally I'm against using view's tags, I prefer creating a subclass and creating a new variable to store the relevant information.

However, if you want to keep using tags, you could use the hash value of the string, so if view.tag == "CLO".hashValue. This is not perfectly equivalent, since "CLO".hashValue will be different from "COL".hashValue, which won't be the case in ObjC. NOTE: As mentioned by @Alexander, the hash value will be different on each launch of the app. If you are persisting data between launches, don't use hashValue

A better alternative would be to create an int-backed enum and add their raw values.

An even better alternative would be to create an option set, make a subclass or UIView or whatever you're using, and add a property to store them there. Then you can check if the view has all the values you need.

Upvotes: 3

vacawama
vacawama

Reputation: 154603

'C', 'L', and 'O' in C-based languages are chars which are 8-bit signed (or unsigned) integers, so their values can be added and compared to an Int.

You were attempting to add "C", "L", and "O" which are Strings so the result with string concatenation is the String "CLO". In Swift, you can't compare a String to an Int. Admittedly, that would have been the better error message.

The equivalent in Swift would be:

if view.tag == UnicodeScalar("C").value + UnicodeScalar("L").value + UnicodeScalar("O").value {

That's really awful for a number of reasons including the fact that order doesn't matter so 'C' + 'L' + 'O' and 'O' + 'C' + 'L' yield the same result. Better alternatives exist in Swift. @EmilioPelaez gives some good alternatives in his answer.

Upvotes: 4

Related Questions