【发布时间】:2018-08-31 15:10:30
【问题描述】:
使用 Xcode 10 (beta 6) 我可以毫无问题地编写和运行以下代码:
import Intents
func test() {
let activity = NSUserActivity(activityType: "com.activtiy.type")
activity.title = "Hello World"
activity.isEligibleForSearch = true
activity.isEligibleForHandoff = false
if #available(iOS 12.0, *) {
activity.isEligibleForPrediction = true
activity.suggestedInvocationPhrase = "Say something"
}
print(activity)
}
从 iOS 12 开始,添加了 .isEligibleForPredictions 和 .suggestedInvocationPhrase 属性,因此 Xcode 10 可以使用 if #available 条件保持代码本身向后兼容。
但是,我想确保此代码与早期版本的 Xcode 向后兼容。在 Xcode 9 中运行时,出现以下错误:
if #available(iOS 12.0, *) {
// ERROR: Value of type 'NSUserActivity' has no member 'isEligibleForPrediction'
activity.isEligibleForPrediction = true
// ERROR: Value of type 'NSUserActivity' has no member 'suggestedInvocationPhrase'
activity.suggestedInvocationPhrase = "Say something"
}
这似乎是因为#available宏实际上是在运行时解析的,因此包含的所有代码仍然需要编译成功。
有没有办法告诉编译器在为 iOS 11 构建或使用 Xcode 9 时忽略这两行代码?
【问题讨论】: