UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

2      

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.

2      

@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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.