swift 2.0 compatibility with iOS 7

I had my swift 1.2 code compatible with ios 7.1 to 8.4. Then when Apple released IOS 9, I migrated my code to swift 2 and my app supports now iOS 8 to 9, but will don't work with iOS 7.

For example, The

try catch
is not compatible with iOS 7 and Xcode mark it as an error.
var error: NSError?
do { 
try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil) 
} catchlet error1 as NSError 
{ error = error1 }

Also I have problems with UIAlertController because xcode gives me the following label

@available(iOS 8.0, *)

how i could make compatible these two problems with iOS7?

Replies

You are mistaking something.

Swift 2 try-catch is bridged to Objective-C error patterns, so using try-catch in iOS7-targeted apps has no problem.

You have an error somewhere, if Xcode mark it as error:

        var error: NSError?
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
        } catch let error1 as NSError {
            error = error1
        }

The code above, compiles without error even if its Deployment Target, set to iOS 7.0 or 7.1.

And I have many sample code using try-catch, they work fine in actual iOS 7.1 device.


And about UIAlertController, if you were using UIAlertController without checking availability, your app crashes at the very point of calling any of the UIAlertController methods, when run on iOS 7 devices.


You needed to write something like this when using UIAlertController, in Swift 1.2:

        if NSClassFromString("UIAlertController") != nil {
            let alertController = UIAlertController(title: "...", message: "...", preferredStyle: .Alert)
            //...
        } else {
            let alertView = UIAlertView(title: "...", message: "...", delegate: nil, cancelButtonTitle: "OK")
            //...
        }

(Swift 1.2 does not show any sort of errors or warnings, if you missed this sort of availability checking, but, as I wrote, that makes your app crash.)


In Swift 2, it should be like this:

        if #available(iOS 8.0, *) {
            let alertController = UIAlertController(title: "...", message: "...", preferredStyle: .Alert)
            //...
        } else {
            let alertView = UIAlertView(title: "...", message: "...", delegate: nil, cancelButtonTitle: "OK")
            //...
        }