I am converting my code from Objective-C to Swift. I declared a function to compare values of two properties and return a Bool
.
And I am confused about why this code not work in Swift.
private var currentLineRange: NSRange?
var location: UInt?
func atBeginningOfLine() -> Bool {
return self.location! == self.currentLineRange?.location ? true : false
}
Compiler gave me an error:
Could not find an overload for == that accepts the supplied arguments
Thanks.
You have two optional values and you want to check if they’re equal. There is a version of
==
for comparing two optionals – but they need to be of the same type.The main problem here is that you are comparing
NSRange.location
, which is aInt
, withlocation
, which is aUInt
. If you tried to do this even without the complication of the optionals, you’d get an error:There’s two ways you can go. Either change
location
to be anInt
, and you’ll be able to use the optional==
:Or, if
location
really does need to be aUInt
for some other reason,map
one of the optionals to the type of the other to compare them:One thing to be careful of –
nil
is equal tonil
. So if you don’t want this (depends on the logic you’re going for), you need to code for it explicitly: