How can I programmatically find Swift's version?
You can use conditional compilation directives to test for the specific Swift version used to build your project:
#if swift(>=5.0)
print("Hello, Swift 5!")
#elseif swift(>=4.0)
print("Hello, Swift 4!")
#elseif swift(>=3.0)
print("Hello, Swift 3!")
#elseif swift(>=2.2)
print("Hello, Swift 2.2!")
#elseif swift(>=2.1)
print("Hello, Swift 2.1!")
#endif
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
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()
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 will give you a nice:
assertion failed: Need Swift 12: file , line 20
UPDATE WWDC 2015 - Swift 2.0
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 3.1 extends the @available
attribute to support specifying Swift version numbers in addition to its existing platform versions.
// Swift 3.1
@available(swift 3.1)
func intVersion(number: Double) -> Int? {
return Int(exactly: number)
}
@available(swift, introduced: 3.0, obsoleted: 3.1)
func intVersion(number: Double) -> Int {
return Int(number)
}