在swift中需要关于类型推断的帮助

时间:2017-07-19 11:16:54

标签: swift swift3 type-inference

当我在swift中阅读关于类型推断时,我开始知道swift足够聪明,可以了解数据类型

就像我写这个程序一样

var v3 = 2+2.5
print("the result is \(v3)")

然后我看到输出

the result is 4.5

但是当我写这个程序时

var v1 = 2.5
var v2 = 2
var v3:Double = v1 + v2
print("the result is \(v3)")

然后它给了我这个错误

ERROR at line 7, col 20: binary operator '+' cannot be applied to operands of type 'Double' and 'Int'
var v3:Double = v1 + v2
                ~~ ^ ~~
NOTE at line 7, col 20: expected an argument list of type '(Double, Double)'
var v3:Double = v1 + v2

所以任何人都可以向我解释这里发生了什么

我在IBM沙箱上完成了这个程序

1 个答案:

答案 0 :(得分:3)

撰写var v3 = 2+2.5时,Swift必须推断出2的类型,这是一个与IntDouble兼容的数字文字。编译器能够这样做,因为同一表达式中有2.5,即Double。因此,编译器得出结论:2也必须是Double。编译器计算总和,并将v3设置为4.5。在运行时不执行任何添加。

当您编写var v2 = 2时,编译器会将2视为Int,同时也会v1Int。现在var v3:Double = v1 + v2上添加了一个,但由于v1v2类型不匹配而失败。

如果您声明var v2:Double = 2,则问题将得到解决。

相关问题