Swift是否支持隐式转换? [英] Does Swift support implicit conversion?

查看:462
本文介绍了Swift是否支持隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下代码:

    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

我收到错误:


'Double'不能转换为'UInt8'

'Double' is not convertible to 'UInt8'

有没有办法隐式转换数据类型(可能仅适用于原始数据类型)?

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

编辑:

我知道如何使用特定类型的构造函数进行显式转换,如 Iducool 所示。但这对我的问题没什么大帮助,因为我们甚至不知道在哪里添加转换。我简化了我在游乐场的表达:

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:

问题在于填充变量,错误信息是

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


'Double'不能转换为'UInt8'。

'Double' is not convertible to 'UInt8'.

所以我做了转换:

然后问题出现在blockWidth变量中。

Then the problem is in "blockWidth" variable now.

我再次添加了转换:

< img src =https://i.stack.imgur.com/TxHV0.pngalt =在此输入图像说明>

错误信息是:


类型'UInt8'不符合协议'FloatLiteralCovertible'

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

最终的工作表达式是:

简单快捷吗?我不这么认为。

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

推荐答案

Swift中没有隐式强制转换。

There is no implicitly cast in Swift.

在swift中简单的转换方式是使用特定类型的构造函数。

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

如果你想让Float从double获得,那么你可以使用 Float(doubleValue)和你一样想要将float转换为整数然后你可以使用 Int(floatValue)

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).

在你的情况下:

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.

注意,当推断浮点数的类型时,Swift总是选择Double(而不是Float)。

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

这篇关于Swift是否支持隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆