问题
I am just trying to use the ceil
or round
functions in Swift but am getting a compile time error:
Ambiguous reference to member 'ceil'.
I have already imported the Foundation
and UIKit
modules. I have tried to compile it with and without the import
statements but no luck. 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())
}
}
回答1:
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
.
So, this code works because c
ends up being a 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:
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:
let a = 0.5
let c = Int(ceil(a))
The same is true of the round()
function, so you'd need the same solution.
回答2:
Depending on the scope of where you call ceil
, you may need to explicitly call Darwin
's ceil
function (deep in a closure, etc). Darwin is imported through Foundation
, which is imported by 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. You would have to explicitly import Glibc
and call Glibc.ceil(myFloat)
instead of using Darwin
.
来源:https://stackoverflow.com/questions/34357739/ambiguous-reference-to-member-when-using-ceil-or-round