Does Swift support implicit conversion?

Bagusflyer picture Bagusflyer · Jul 9, 2014 · Viewed 22.6k times · Source

For example, I have the following code:

    let numberOfBlocks = 3
    let blockWidth = SKSpriteNode(imageNamed: "image.png").size.width
    let padding = 20.0

    let offsetX : Float = (self.frame.size.width - (blockWidth * numberOfBlocks + padding * (numberOfBlocks-1))) / 2

I got the error:

'Double' is not convertible to 'UInt8'

Is there a way to implicitly convert the data type (maybe only for primitive data type)?

Edit:

I know how to do the explicit conversion by using constructor of particular type as Iducool suggested. But it's not a big help to my question because we even don't know where to add the conversions. I simplified my expression in playground:

enter image description here

The problem is in "padding" variable, the error message is

'Double' is not convertible to 'UInt8'.

So I did the conversion:

enter image description here

Then the problem is in "blockWidth" variable now.

I added the conversion again:

enter image description here

And error message is:

Type 'UInt8' does not conform to protocol 'FloatLiteralCovertible'

The final working expression is:

enter image description here

Is it simple and swift? I don't think so.

Answer

Iducool picture Iducool · Jul 9, 2014

There is no implicitly cast in Swift.

Easy way of conversion in swift is using constructor of particular type.

Like if you want to get Float from double then you can use Float(doubleValue) and Same way if you want to convert float to integer then you can use Int(floatValue).

In your case:

let intValue = UInt8(doubleValue)

Beware that you will lose any value after the decimal point. So, choose a better way. Above conversion is just to help you in understanding.

Note that Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.