ykt68
ykt68

Reputation: 61

'import UIKit' caused disappearing a cast error of Double-to-Int. Why ?

I'm a Swift beginner and I have a question.

I created a new playground file in Xcode6-Beta3 , and erased
all default snippets generated automatically. And I wrote following
one line only,

var x:Int = (1.234 as Int)

And then, this line caused a compile error with message saying that

Playground execution failed: 
error: <EXPR>:1:20: error: 
'Double' is not convertible to 
'Int'
var x:Int = (1.234 as Int)
               ^

in the Console Output. I can understand this error because 1.234 can not be casted as Int.

Next, I added one more line import UIKit before var x:Int = (1.234 as Int),
so the codes were following:

import UIKit

var x:Int = (1.234 as Int)

Then, the error message above disappeared. But I can't understand
the reason that adding import UIKit caused disappearing
the error message claiming that
'Double' is not convertible to 'Int'
above.

Please teach me this reason or some references to understand about it.

Regards.

Upvotes: 2

Views: 204

Answers (1)

onevcat
onevcat

Reputation: 4631

The compiler will always seek a way to make your code compiling as possible as it can. With import UIKit, your code is something equivalent to

var _x = 1.234 as NSNumber
var x:Int = (_x as Int)

The compiler can turn to NSNumber when have UIKit imported.

Upvotes: 1

Related Questions