Maiko Ohkawa
Maiko Ohkawa

Reputation: 933

Binary operator '<' cannot be applied to operands of type 'Double' and 'CGFloat'

This code has no syntax error.

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

On the other hand, the below code has an syntax error. Error Message: Binary operator '<' cannot be applied to operands of type 'Double' and 'CGFloat'

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

Why it happend? I tried to use if let instead of force unwrap, but I had the same error.

Environment: Xcode7.0.1 Swift2

Upvotes: 4

Views: 11286

Answers (3)

Sreekanth G
Sreekanth G

Reputation: 692

Please check this one on 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
}

Upvotes: 1

Abizern
Abizern

Reputation: 150615

A slightly classier way to do this is with the stride() family of functions.

// 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.
}

Upvotes: 4

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Because image!.size.height return CGFloat any type of your n is Double so you need to convert your CGFloat to Double this way Double(image!.size.height).

And your code will be:

let image = UIImage(named: "myImage")

for (var n = 1.0; n < Double(image!.size.height); n += 0.1) {

}

Or you can assign type to n as CGFloat this way:

for (var n : CGFloat = 1.0; n < image!.size.height; n += 0.1) {

}

Upvotes: 6

Related Questions