CodeSmile
CodeSmile

Reputation: 64477

How to fix 'Int' is not convertible to 'String' in a comparison that uses only Int?

Imagine my surprise that this Swift code generates an error in Xcode 6.1.1:

public func unlockNextLevel() -> Int
{
    var highest : Int = 123
    return (highest < highestUnlockedLevel)
}

More precisely, it tells me that in the return line:

'Int' is not convertible to 'String'

So, since I had some of these weird conversion errors before, I thought I'll try converting both types to Int and see what I get:

public func unlockNextLevel() -> Int
{
    var highest : Int = 123
    return (Int(highest) < Int(highestUnlockedLevel))
}

I then get the following error on the return line:

Could not find an overload for '<' that accepts the supplied arguments

But when I break it down to just constant values:

return (Int(3) < Int(12))

I get the int not convertible to string error again.

'Int' is not convertible to 'String'

Gnnnnn.... oh-kay, so I give it another shot without the brackets:

return highest < highestUnlockedLevel

This then gives me yet another error message:

Cannot invoke '<' with an argument list of type '(@lvalue Int, @lvalue Int)'

Okay, I get it Swift, I'm stoopid. Or maybe ... hmmm, take this, Swift:

var result = highest < highestUnlockedLevel
return result

Arrrr ... nope. Swift decides that now the return line constitutes yet another error:

'Bool' is not convertible to 'Int'

(... dials number for psych evaluation ...)


So ... could someone explain to me:

Note: This is in a mixed Objc/Swift project if that makes any difference. The highestUnlockedLevel variable is declared in a Swift class with custom setter and getter.

Upvotes: 0

Views: 967

Answers (1)

Kirsteins
Kirsteins

Reputation: 27345

(highest < highestUnlockedLevel) produces Bool not Int (unlike Objective-C where it returns int that can be automatically converted to BOOL), thats why you get the error. But certainly its wrong and misleading error as the problem is that Bool cannot be converted to Int.

Upvotes: 1

Related Questions