如何将后卫声明与条件完美地结合在一起?

时间:2019-01-10 11:39:13

标签: swift guard-statement

我目前有保护声明:

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

但是,如果变量needsQuota == true,我 想要执行保护块。如果要使用needsQuota == false,我想跳过保护声明。有没有比带返回的if语句更好的方法呢?

编辑:

如何将其简化为一个防护?

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

3 个答案:

答案 0 :(得分:1)

怎么样:

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

答案 1 :(得分:1)

问题在于,如果您的if条件失败或您的guard失败,您希望以不同的方式继续执行,因此您无法将它们真正组合为一个guard。但是,您可以通过将if条件的否定版本放在guard语句中,将这两个条件组合成if语句。

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

答案 2 :(得分:0)

这不行吗?

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