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

Isn;t Swift a type safe language

Forums > Swift

@boon  

Why does the compiler allow

print(1 + 3.0)

Even more strangely, it disallows

let x = 1

let z = 3.0 + x

print(z)

But allows

let x = 3.0

let z = x + 1

print(z)

I do not understand the logic and on what basis does it type check or not type check

2      

Swift is a type-safe language but it also supports type inference.

This means that when you don't explicitly specify the type of a variable, the compiler tries to guess what type it is. And sometimes it guesses wrong. (Well, not much wrong as it doesn't have enough context to determine what you really want.)

In the example:

print(1 + 3.0)

the compiler assumes that 1 is an Int. But then it encounters 3.0, which is a Double rather than an Int. So it backtracks and assigns the type Double to 1 and your print statement prints the result of adding two Doubles.

Here:

let x = 1

let z = 3.0 + x

print(z)

the compiler decides that x is an Int and then moves on the next statement. But then it sees z = 3.0 + x, where 3.0 is a Double literal, and realizes you are trying to add a Double and an Int, which you cannot do, so it chokes. The compiler cannot figure out that x should be a Double because it has already decided it should be an Int and continued processing your code.

With:

let x = 3.0

let z = x + 1

print(z)

x is declared as a Double (because you assigned the literal 3.0). z then becomes Double plus Int, except that, as in the first example, the compiler is able to figure out that 1 should be a Double instead of an Int so z is assigned the result of adding two Doubles.

The difference between the second and third examples is that the compiler has contextual clues that x should be a Double in the latter but lacks those clues in the former.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.