Check OS version in Swift?

For iOS, try:

var systemVersion = UIDevice.current.systemVersion

For OS X, try:

var systemVersion = NSProcessInfo.processInfo().operatingSystemVersion

If you just want to check if the users is running at least a specific version, you can also use the following Swift 2 feature which works on iOS and OS X:

if #available(iOS 9.0, *) {
    // use the feature only available in iOS 9
    // for ex. UIStackView
} else {
    // or use some work around
}

BUT it is not recommended to check the OS version. It is better to check if the feature you want to use is available on the device than comparing version numbers. For iOS, as mentioned above, you should check if it responds to a selector; eg.:

if (self.respondsToSelector(Selector("showViewController"))) {
    self.showViewController(vc, sender: self)
} else {
    // some work around
}

Update:
Now you should use new availability checking introduced with Swift 2:
e.g. To check for iOS 9.0 or later use can this:

if #available(iOS 9.0, *) {
  // use UIStackView
} else {
  // show sad face emoji
}

or can be used with whole method or class

@available(iOS 9.0, *)
func useStackView() {
    // use UIStackView
}    

or with guard

guard #available(iOS 14, *) else {
    return
}

For more info see this.

UPDATE: based on Allison's comment I have updated the answer, check is still runtime, but compiler can know in advance & can show better error or suggestion while you are working on it.

Other ways to check:

if you don't want exact version but want to check iOS 9,10 or 11 using if:

let floatVersion = (UIDevice.current.systemVersion as NSString).floatValue

EDIT: Just found another way to achieve this:

let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1)
let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1)

Tags:

Ios

Macos

Swift