Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

ios - Does Swift support implicit conversion?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...