Swift可用性检查不包括macOS [英] Swift availability check exclude macOS

查看:83
本文介绍了Swift可用性检查不包括macOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个代码,希望在iOS 13或更高版本上执行.因此,我正在使用标准的可用性检查:

I have a code in my app which I want to execute on iOS 13 or later. So, I was using a standard availability check:

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版本.

Color is a typealias which casts to UIColor on iOS and NSColor on macOS. I am kind of trying to create macOS version of my target with as little if..else as possible.

上面的代码应与NSColor一样工作,具有许多与UIColor相同的初始化方法.问题是,当我构建我的macOS目标时,它会抱怨systemGray6.因此,出于我未知的原因,macOS目标通过了#available(iOS 13.0, *)检查!

The code above should work as NSColor has many of the same init methods as UIColor. The problem is that when I build my macOS target it complains about systemGray6. So, for a reason unknown to me, macOS target passes #available(iOS 13.0, *) check!

为什么会发生这种情况,如何预防呢?

Why does it happen and how can I prevent it?

推荐答案

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

When you use if #available(iOS 13.0, *) you're basically saying: do this on iOS 13.0 and later, and on all other operating systems - that's what the * means.

在特定情况下,您将需要排除macOS,因为NSColor没有systemGrayX吸气剂:

In your specific case, you'll need to exclude macOS, since NSColor does not have the systemGrayX getters:

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

这篇关于Swift可用性检查不包括macOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆