KexAri
KexAri

Reputation: 3977

Why wont this conditional work in Swift 3?

Hey prior to Swift 3 I previously used :

if CustomUser.sharedInstance.numberOfCredits > 0 {
}

Where numberOfCredits is Double?. Now I get the error: Binary operator '>' cannot be applied to operands of type 'Double?' and 'Int'. Why is this? So I change 0 to 0.0 and get Binary operator '>' cannot be applied to operands of type 'Double?' and 'Double'. Why doesn't this line work in Swift 3?

Upvotes: 0

Views: 1121

Answers (3)

Wilson
Wilson

Reputation: 9136

struct CustomerUser {
  static var sharedInstance = Instance()
}

struct Instance {
  var numberOfCredits: Double?
}

let credits = CustomerUser.sharedInstance.numberOfCredits ?? 0.0

if credits > 0 {
  print("credits greater than zero")
}

numberOfCredits is an Optional Double (Double?) means it may contain a nil or a Double value.

That's why compiler wouldn't know what to do if numberOfCredits were nil.

if CustomUser.sharedInstance.numberOfCredits > 0 // wtf 🙈

In order to convert Double? to Double, you might use the ?? operator which not only will convert in case numberOfCredits contains a Double value but in case numberOfCredits contains nil will return 0.0, how cool that is? 💪💪

let credits = CustomerUser.sharedInstance.numberOfCredits ?? 0.0

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Swift 3 has removed comparisons between an optional and a non-optional with the same base type. You have three options to handle this:

  • Explicitly unwrap the value with ! if you know that it is non-nil,
  • Use if let construct to unwrap the optional,
  • Use nil coalescing operator

Here is how you can use the third option:

if CustomUser.sharedInstance.numberOfCredits ?? 0 > 0 {
}

Note: There is a possibility that numberOfCredits is optional by omission - for example, because sharedInstance is defined as optional without automatic unwrapping. In this case it is better to fix the underlying problem, rather than using ?? or ! as a workaround.

Upvotes: 2

hnh
hnh

Reputation: 14795

This doesn't work because your numberOfCredits is an Optional (Double?). Should be: 0121 Remove Optional Comparison Operators.

Do it like this:

if let v = CustomUser.sharedInstance.numberOfCredits, v > 0 {
}

P.S.: Apart from that: numberOfCredits sounds like it should be an Int, not a Double? And maybe it shouldn't be an Optional either - if there are no credits, it should be 0? Hard to say w/o knowing what you are doing.

Upvotes: 5

Related Questions