我怎样才能以编程方式找到Swift的版本? [英] How can I programmatically find Swift's version?

查看:109
本文介绍了我怎样才能以编程方式找到Swift的版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以找到我现在正在运行的Swift版本恢复到终端并输入:

I know I can find the version of Swift I'm running right now reverting to a Terminal and typing:

xcrun swift --version
Swift version 1.1 (swift-600.0.57.4)
Target: x86_64-apple-darwin13.4.0

另外,我一直在阅读预处理器宏,但没有找到Swift版本常量的运气。

Also, I've been reading about the Preprocessor Macros in Swift, but no luck finding a Swift version constant.

随着Swift 1.2的临近,标记仅在Swift 1.1上运行的旧代码(Xcode高达6.2)或需要Xcode 6.3的新代码(Swift 1.2)

As Swift 1.2 approaches it will be nice to flag old code that only runs on Swift 1.1 (Xcode up to 6.2) or new code that needs Xcode 6.3 (Swift 1.2)

注意:我也可以使用system()来执行以下操作:

Note: I can also use system() to do something like:

system("xcrun swift --version | grep version > somefile.txt")

然后打开somefile.txt,而不是更喜欢一些更简单的解决方案

Then open somefile.txt, but rather prefer some simpler solution

推荐答案

最后得到了解决方法来执行此操作。我正在使用前缀为 __ 的常量,您可以在Playground中观察。对于某些级别的反射,这会更容易,但.. 。

Finally got a workaround to do this. I'm using the constants prefixed with __ you can observe in your Playground. This would have been easier with some level of reflection, but...

__ IPHONE_OS_VERSION_MAX_ALLOWED 是80200,意为 __ IPHONE_8_2 for Xcode 6.2(​​Swift 1.1)但Xcode 6.3(Swift 1.2)中的值为80300( __ IPHONE_8_3

__IPHONE_OS_VERSION_MAX_ALLOWED is 80200, meaning __IPHONE_8_2 for Xcode 6.2 (Swift 1.1) but its value is 80300 (__IPHONE_8_3) in Xcode 6.3 (Swift 1.2)

func isSwift12() -> Bool {
  return __IPHONE_OS_VERSION_MAX_ALLOWED == 80300
}

isSwift12()

所以现在你的图书馆你可以快速失败并告诉你的用户Swift的版本使用不正确:

So now in your library you can fail fast and tell your user Swift's version is not correct using this:

assert(isSwift12(), "Need Swift 12")

Swift会给你一个很好的:

Swift will give you a nice:


断言失败:需要Swift 12:文件,第20行

assertion failed: Need Swift 12: file , line 20

更新WWDC 2015 - Swift 2.0

如Apple的 Swift博客,在Swift 2.0中我们有 #available 块来检查某些我们的代码中的OS版本。一个例子应该是:

As stated in Apple's Swift blog, in Swift 2.0 we have #available blocks to check for certain OS versions in our code. An example should be:

if #available(OSX 10.11, *) {
    monochromeFilter!.setValue(CIColor(red: 0.5, green: 0.5, blue: 0.5), forKey:kCIInputColorKey)
} else {
    // Fallback on earlier versions
}

这篇关于我怎样才能以编程方式找到Swift的版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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