我目前有保护声明:
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()
}
}
答案 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()
}