Swift 运算符报错
var radius = 4
let pi = 3.14159
var area = radius * radius * pi
In case you’ve forgotten from math class, this computes the area of a circle. ;]
You might be surprised to see the compiler complain about the second multiplication operation with the error, cannot invoke ‘*’ with an argument list of type ‘($T4, Double).
What exactly does this mean?
All operations are defined as functions, and the above indicates that the compiler cannot find a multiplication function that takes an Int on the left hand side and a Double on the right.
以防你忘记数学公式,这个是等式用来计算圆的面积。
你可能会惊讶编译器对第二个乘法操作报错,当参数类型是“Double”时不能调用“*”,这究竟是怎么回事?(在Swift中)所有的运算符都被定义为函数,以上的例子表明编译器找不到一个函数,这个函数的左边的参数是Int类型右边是Double类型
This illustrates a very important feature of the Swift language: all numeric type conversions must be explicit regardless of whether you want to convert to a type with more or less precision. This is true of integers as well as floating point numbers.
To fix the problem, update the code as follows:
var area = Double(radius) * Double(radius) * pi
这个例子是Swift语言非常重要的特性:所有的数字类型之间的转换必须是明确,清晰的,无论你是想提升或者降低精确度。这也适用于整数和浮点数。为了解决这个问题,按照以下的形式修改代码: