为什么 Swift 在使用文字时会推断出双精度值? [英] Why is Swift inferring double values when using literals?

查看:25
本文介绍了为什么 Swift 在使用文字时会推断出双精度值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Swift 对类型非常严格,并且不会将一种类型隐式转换为另一种类型.

I understand that Swift is very strict about types and does not implicitly cast one type to another.

为什么这不会产生错误并且输出是一个双精度数组?

Why does this not generate an error and the output is an array of doubles?

let myDoubles = [Double.Pi, 42]

但这是吗?

let fortyTwoInt = 42;
let myDoubles = [Double.Pi, one]

为什么在第一个示例中隐式地将 42 转换为 42.0?如果它不是铸造,还会发生什么?

Why does it implicitly cast 42 to 42.0 in the first example? And if it is not casting, what else is happening?

更简单的例子:

let someFloat = 2.0 + 2

对比

let twoInt = 2
let someFloat = 2.0 + twoInt

同样,后者不起作用.

推荐答案

Cast"在这里并不是真正正确的词.它将字符序列4"和2"解释为整数文字.Double 符合 ExpressibleByIntegerLiteral,因此可以从中构造 Double.

"Cast" is not really the right word here. It interprets the character sequence "4" and "2" as an integer literal. Double conforms to ExpressibleByIntegerLiteral, so the Double can be constructed from it.

fortyTwoInt 不是整数文字.这是一个Int.并且 Swift 不会自动在 IntDouble 之间转换.

fortyTwoInt is not an integer literal. It's an Int. And Swift will not automatically convert between Int and Double.

这篇关于为什么 Swift 在使用文字时会推断出双精度值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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