【问题标题】:Swift availability check exclude macOSSwift 可用性检查不包括 macOS
【发布时间】:2020-09-03 03:53:21
【问题描述】:

我的应用中有一个代码,我想在 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 相同的init 方法。问题是,当我构建我的 macOS 目标时,它会抱怨 systemGray6。因此,出于我不知道的原因,macOS 目标通过了#available(iOS 13.0, *) 检查!

为什么会发生,我该如何预防?

【问题讨论】:

    标签: ios swift macos conditional-compilation


    【解决方案1】:

    当您使用 if #available(iOS 13.0, *) 时,您基本上是在说:在 iOS 13.0 及更高版本上执行此操作,在所有其他操作系统上 - 这就是 * 的含义。

    在您的具体情况下,您需要排除 macOS,因为 NSColor 没有 systemGrayX getter:

    #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)
    

    【讨论】:

    • 想要避免使用#ifs,但您正确地指出else 是不必要的,因为return 声明。我猜不可能只在#available 检查中指定iOS? :)
    • 不,我不知道。
    • 能够使用#available(iOS 13, !macOS, *) 会很高兴
    • 希望我们能尽快获得这个能力:forums.swift.org/t/…
    【解决方案2】:

    你可以像这样简单地声明:

    #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
    

    【讨论】:

    • 对我希望从 13.0 开始仅在 iOS 上提供的 Color.systemGray6 有何帮助?
    猜你喜欢
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多