Gergely Gergely - 1 month ago 6
Swift Question

Check OS version in Swift?

I'm trying to check system information in Swift. I figured out, that it could be achieved by code:

var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)


I have two problems with this code:


  1. What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.

  2. How can I read information from sysData?


Answer

For iOS, try:

var systemVersion = UIDevice.currentDevice().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. Better check if the feature you want to use is available on the device then 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
}