WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Comparison operators

Forums > 100 Days of Swift

why these lines are valid in swift

var a = 3.3
a > 3

and these are not


var a = 3.3
var b = 3
a > b

is that because swift treat 3 as double

   

In the first case - yes, and in the second case - no.

In 'a > 3', the '3' is a constant number literal, and the compiler will have methods to widen the type definition to match the lhs of the comparator, in this case to a 'double'

For 'a > b', 'a' and 'b' already have defined types of 'Double' and 'Int', and the compiler has no method defined to compare an 'Int' with a 'Double'.

You could overcome that limitation by either type casting 'b' to be a 'Double' or by writing your own extension for the '>' operator.

In this simple example type casting is the easiest solution, however, it would be a good opportunity to practice writing an extension for the '>' operator, as writing extensions to existing operators and functions is more likely when you have more complicated data types and structures.

   

@Greenamberred is correct. As Swift is type safe.

So this obviously will not work

var a = 3.3
var b = "3"
a > b

While writing an extension will work, it easier to make sure that the type match which is safer as you might make a mistake somewhere else,

You can either do var b = 3.0 which will imply that b a Double or do var b: Double = 3

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.