使用 ceil 或 round 时对成员的不明确引用 [英] Ambiguous reference to member when using ceil or round

查看:43
本文介绍了使用 ceil 或 round 时对成员的不明确引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在 Swift 中使用 ceilround 函数,但出现编译时错误:

I am just trying to use the ceil or round functions in Swift but am getting a compile time error:

对成员ceil"的不明确引用.

Ambiguous reference to member 'ceil'.

我已经导入了 FoundationUIKit 模块.我尝试使用和不使用 import 语句编译它,但没有运气.有谁知道我做错了什么?我的代码如下;

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())

    }
   }

推荐答案

出现这个问题的原因可能是一开始看起来很奇怪,但很容易解决.

This problem occurs for something that might seem strange at first, but it's easily resolved.

简单地说,您可能认为调用 ceil() 会将浮点数四舍五入到最接近的整数,但实际上它根本不返回整数:如果您给它一个 Float 它返回一个 Float,如果你给它一个 Double 它返回一个 Double.

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.

所以,这段代码之所以有效是因为 c 最终变成了 Double:

So, this code works because c ends up being a Double:

let a = 0.5
let c = ceil(a)

...而这段代码会导致您的确切问题,因为它试图在没有类型转换的情况下将 Double 强制转换为 Int:

…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)

解决办法是将ceil()的返回值转换为整数,像这样:

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))

round() 函数也是如此,因此您需要相同的解决方案.

The same is true of the round() function, so you'd need the same solution.

这篇关于使用 ceil 或 round 时对成员的不明确引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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