Kex
Kex

Reputation: 8579

How to elegantly combine a guard statement with a condition?

I currently have the guard statement:

 guard let designationQuota = Defaults.quotas.value?.designationQuota, designationQuota > 0 else {
      return AppDelegate.shared.presentNoDesignationQuotaWarning()
 }

however I only want to do the guard block if the variable needsQuota == true. I want to skip the guard statement if needsQuota == false. Is there a nicer way of doing this over than an if statement with a return?

EDIT:

How do I simplify this into a single guard?

if needsQuota {
  guard let designationQuota = Defaults.quotas.value?.designationQuota, designationQuota > 0 else {
      return AppDelegate.shared.presentNoDesignationQuotaWarning()
   }
}

Upvotes: 1

Views: 950

Answers (3)

henrik-dmg
henrik-dmg

Reputation: 1493

Wouldn‘t this do the trick?

guard needsQuota, let designationQuota = Defaults.quotas.value?.designationQuota, designationQuota > 0 else {
    return AppDelegate.shared.presentNoDesignationQuotaWarning()
}

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54706

The problem is that you want to continue execution differently in case your if condition fails or in case your guard fails, so you cannot really combine them into a single guard. However, you could combine the two conditions into an if statement by putting the negated version of your guard condition in the if statement.

if needsQuota && (Defaults.quotas.value?.designationQuota ?? 0 <= 0) {
    return AppDelegate.shared.presentNoDesignationQuotaWarning()
}

Upvotes: 1

ielyamani
ielyamani

Reputation: 18581

How about :

guard !needsQuota ||
    (Defaults.quotas.value?.designationQuota.map { $0 > 0 } == true) else {
    return AppDelegate.shared.presentNoDesignationQuotaWarning()
}

Upvotes: 0

Related Questions