Swift 可用性检查排除 macOS
Swift availability check exclude macOS
我的应用程序中有一段代码,我想在 iOS 13 或更高版本上执行。所以,我使用的是标准可用性检查:
if #available(iOS 13.0, *) {
return Color.systemGray6.resolvedColor(with: trait!)
} else {
return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
}
Color
是一个类型别名,它在 iOS 上转换为 UIColor
,在 macOS 上转换为 NSColor
。我有点想用尽可能少的 if..else
创建我的目标的 macOS 版本。
上面的代码应该可以工作,因为 NSColor
有许多与 UIColor
相同的初始化方法。问题是,当我构建我的 macOS 目标时,它会抱怨 systemGray6
。因此,由于我不知道的原因,macOS 目标通过了 #available(iOS 13.0, *)
检查!
为什么会发生,我该如何预防?
当您使用 if #available(iOS 13.0, *)
时,您基本上是在说:在 iOS 13.0 及更高版本、 和所有其他操作系统 上执行此操作 - 就是这样*
表示。
在您的特定情况下,您需要排除 macOS,因为 NSColor 没有 systemGrayX
吸气剂:
#if os(iOS)
if #available(iOS 13.0, *) {
return Color.systemGray6
}
#endif
return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
您可以像这样简单地声明:
#if os(macOS)
import AppKit
public typealias Color = NSColor
#else
import UIKit
public typealias Color = UIColor
#endif
然后您可以在 iOS 和 MacOS 中使用 Color:
Color.Black // will work for both
我的应用程序中有一段代码,我想在 iOS 13 或更高版本上执行。所以,我使用的是标准可用性检查:
if #available(iOS 13.0, *) {
return Color.systemGray6.resolvedColor(with: trait!)
} else {
return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
}
Color
是一个类型别名,它在 iOS 上转换为 UIColor
,在 macOS 上转换为 NSColor
。我有点想用尽可能少的 if..else
创建我的目标的 macOS 版本。
上面的代码应该可以工作,因为 NSColor
有许多与 UIColor
相同的初始化方法。问题是,当我构建我的 macOS 目标时,它会抱怨 systemGray6
。因此,由于我不知道的原因,macOS 目标通过了 #available(iOS 13.0, *)
检查!
为什么会发生,我该如何预防?
当您使用 if #available(iOS 13.0, *)
时,您基本上是在说:在 iOS 13.0 及更高版本、 和所有其他操作系统 上执行此操作 - 就是这样*
表示。
在您的特定情况下,您需要排除 macOS,因为 NSColor 没有 systemGrayX
吸气剂:
#if os(iOS)
if #available(iOS 13.0, *) {
return Color.systemGray6
}
#endif
return Color(red: 0.082, green: 0.118, blue: 0.161, alpha: 1.0)
您可以像这样简单地声明:
#if os(macOS)
import AppKit
public typealias Color = NSColor
#else
import UIKit
public typealias Color = UIColor
#endif
然后您可以在 iOS 和 MacOS 中使用 Color:
Color.Black // will work for both