0

I have lots of code in my project of this style:

let hasQuestionsRemaining = user.numberOfCredits > 0.0

where numberOfCredits is a Double?. So I get the error : Binary operator '>' cannot be applied to operands of type 'Double?' and 'Double'.

So now I use:

var hasQuestionsRemaining = false
if let numberOfCredits = user.numberOfCredits, numberOfCredits > 0.0 {
   hasQuestionsRemaining = true
}

Is there a more efficient way to do this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
KexAri
  • 3,867
  • 6
  • 40
  • 80

1 Answers1

0

In Swift 2.2, you used to be able to compare Optional and non-Optional types directly, but that behaviour has been removed in Swift 3.0. You can read more about it in proposal SE-0121.

Swift 3.0 leaves it to developers to handle their optionals in a way that's most appreciate to their application. In your case, this seems like the way to go:

let hasQuestionsRemaining = user.numberOfCredits ?? 0.0 > 0.0

It'll treat nil values as 0.0 for the sake of comparison to 0.0.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Alexander
  • 59,041
  • 12
  • 98
  • 151