在SwiftUI中使用if语句判断:
// 用户未完成内购,图片列表不为空,图片列表中有小于5MB的图片
// 或者用户完成内购,图片不为空
// 满足以上任一条件,显示下载和清除队列按钮
if !appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty && appStorage.images.contains { $0.inputSize < 5_000_000 } ||
appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty {
// 代码部分
}
在contains一行提示:
Trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning
Replace ' { $0.inputSize < 5_000_000 }' with '(where: { $0.inputSize < 5_000_000 })'
点击Fix按钮后,自动转变为:
appStorage.images.contains(where: { $0.inputSize < 5_000_000 })
这个报错提示在于,Swift在if条件中,使用了contains { } 这种尾随闭包。
编译器有时候会误认为 { $0.inputSize < 5_000_000 } 是if的主体,而不是contains的参数。
Swift 5.7+编译方面更加严格,会提示使用显式参数标签:
appStorage.images.contains(where: { $0.inputSize < 5_000_000 })
这是标准写法,也能消除警告。
因此,代码的写法为:
// 用户未完成内购,图片列表不为空,图片列表中有小于5MB的图片
// 或者用户完成内购,图片不为空
// 满足以上任一条件,显示下载和清除队列按钮
if !appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty && appStorage.images.contains(where: { $0.inputSize < 5_000_000 }) ||
appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty {
// 代码部分
}
为了代码的可读性,可以添加括号:
if (!appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty && appStorage.images.contains (where: { $0.inputSize < 5_000_000 })) ||
(appStorage.inAppPurchaseMembership && !appStorage.images.isEmpty) {
// 显示下载和清除队列按钮
}
这个写法增加了可读性,编译器也不会提示尾随闭包混淆的问题。