[英]Ambiguous reference to member when using ceil or round
I am just trying to use the ceil
or round
functions in Swift but am getting a compile time error: 我只是想在Swift中使用
ceil
或round
函数但是我遇到了编译时错误:
Ambiguous reference to member 'ceil'.
对成员'ceil'的模棱两可的提及。
I have already imported the Foundation
and UIKit
modules. 我已经导入了
Foundation
和UIKit
模块。 I have tried to compile it with and without the import
statements but no luck. 我曾尝试使用和不使用
import
语句编译它,但没有运气。 Does anyone one have any idea what I am doing wrong? 有谁知道我做错了什么? my code is as follow;
我的代码如下;
import UIKit
@IBDesignable class LineGraphView: GraphView {
override func setMaxYAxis() {
self.maxYAxis = ceil(yAxisValue.maxElement())
}
}
This problem occurs for something that might seem strange at first, but it's easily resolved. 这个问题最初可能看起来很奇怪,但很容易解决。
Put simply, you might think calling ceil()
rounds a floating-point number up to its nearest integer, but actually it doesn't return an integer at all: if you give it a Float
it returns a Float
, and if you give it a Double
it returns a Double
. 简而言之,您可能会认为调用
ceil()
将浮点数ceil()
到最接近的整数,但实际上它根本不返回整数:如果给它一个Float
它会返回一个Float
,如果你给它一个Double
它返回一个Double
。
So, this code works because c
ends up being a Double
: 所以,这段代码有效,因为
c
最终成为Double
:
let a = 0.5
let c = ceil(a)
…whereas this code causes your exact issue because it tries to force a Double
into an Int
without a typecast: ...而此代码会导致您的确切问题,因为它试图强制
Double
进入Int
而不进行类型转换:
let a = 0.5
let c: Int = ceil(a)
The solution is to convert the return value of ceil()
to be an integer, like this: 解决方案是将
ceil()
的返回值转换为整数,如下所示:
let a = 0.5
let c = Int(ceil(a))
The same is true of the round()
function, so you'd need the same solution. round()
函数也是如此,因此您需要相同的解决方案。
Depending on the scope of where you call ceil
, you may need to explicitly call Darwin
's ceil
function (deep in a closure, etc). 根据你调用
ceil
的范围,你可能需要显式调用Darwin
的ceil
函数(深入闭包等)。 Darwin is imported through Foundation
, which is imported by UIKit
. 达尔文通过
Foundation
进口,该Foundation
由UIKit
进口。
let myFloat = 5.9
let myCeil = Darwin.ceil(myFloat) // 6
On linux, Glibc
is used in place of Darwin
for C-level API access. 在linux上,使用
Glibc
代替Darwin
进行C级API访问。 You would have to explicitly import Glibc
and call Glibc.ceil(myFloat)
instead of using Darwin
. 您必须显式
import Glibc
并调用Glibc.ceil(myFloat)
而不是使用Darwin
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.