二元运算符'<'不能应用于'Double'和'CGFloat'类型的操作数

时间:2015-10-03 09:29:45

标签: swift swift2

此代码没有语法错误。

for (var m = 1.0; m < 3.0; m += 0.1) {
}

另一方面,下面的代码有语法错误。 错误消息:二元运算符'&lt;'不能应用于'Double'和'CGFloat'类型的操作数

let image = UIImage(named: "myImage")
for (var n = 1.0; n < image!.size.height; n += 0.1) {
}

为什么会这样?我尝试使用if let而不是强制解包,但我遇到了同样的错误。

环境: Xcode7.0.1 Swift2

3 个答案:

答案 0 :(得分:6)

由于image!.size.height返回CGFloat任何类型的n都是Double,因此您需要将CGFloat转换为Double这种方式{ {1}}。

您的代码将是:

Double(image!.size.height)

或者您可以通过这种方式将let image = UIImage(named: "myImage") for (var n = 1.0; n < Double(image!.size.height); n += 0.1) { } 类型指定为n

CGFloat

答案 1 :(得分:4)

执行此操作的一种稍微有点的方法是使用stride()函数族。

// Create the image, crashing if it doesn't exist. since the error case has been handled, there is no need to force unwrap the image anymore.
guard let image = UIImage(named: "myImage") else { fatalError() }

// The height parameter returns a CGFloat, convert it to a Double for consistency across platforms.
let imageHeight = Double(image.size.height)

// Double conforms to the `Strideable` protocol, so we can use the stride(to:by:) function to enumerate through a range with a defined step value.
for n in 1.0.stride(to: imageHeight, by: 0.1) {
    print("\(n)")
    // ... Or do whatever you want to in here.
}

答案 2 :(得分:0)

请在Swift 4.0上选中此

var enteringAmountDouble: Double? {
    return Double(amountTextField.text!)
}
var userMoneyDouble: Double? = userWalletMerchants?.balance
if (enteringAmountDouble?.isLessThanOrEqualTo(userMoneyDouble!))! {
    print("Balance is there .. U can transfer money to someone!")
}else{
    APIInterface.instance().showAlert(title: "Please check you are balance", message: "Insufficient balance")
    return
}