Objective-C 在 XCode 9+ / LLVM 5+ 中有一个@available
表达式,允许您将代码块保护到至少某个操作系统版本,这样如果您使用仅在该操作系统上可用的 API,它就不会发出未保护的可用性警告操作系统版本。
问题是这种可用性保护只有在它是if
. 如果您在任何其他上下文中使用它,您会收到警告:
@available does not guard availability here; use if (@available) instead
因此,例如,如果您尝试将可用性检查与以下条件中的其他条件相结合,则它不起作用if
:
if (@available(iOS 11.0, *) && some_condition) {
// code to run when on iOS 11+ and some_condition is true
} else {
// code to run when on older iOS or some_condition is false
}
if
任何在块内或仍然使用 iOS 11 API 的代码some_condition
都会生成不受保护的可用性警告,即使保证只有在 iOS 11+ 上才能访问这些代码。
我可以把它变成两个嵌套if
的 s,但是else
代码必须被复制,这很糟糕(特别是如果它有很多代码):
if (@available(iOS 11.0, *)) {
if (some_condition) {
// code to run when on iOS 11+ and some_condition is true
} else {
// code to run when on older iOS or some_condition is false
}
} else {
// code to run when on older iOS or some_condition is false
}
else
我可以通过将块代码重构为匿名函数来避免重复,但这需要在else
之前定义块if
,这使得代码流难以遵循:
void (^elseBlock)(void) = ^{
// code to run when on older iOS or some_condition is false
};
if (@available(iOS 11.0, *)) {
if (some_condition) {
// code to run when on iOS 11+ and some_condition is true
} else {
elseBlock();
}
} else {
elseBlock();
}
任何人都可以提出更好的解决方案吗?