Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


Code sample: NSError and Swift 2.0

This is a follow up on a previous post about the NSError (pointer).

In Swift 2.0 the NSError in the NSFileManager calls have been replaced with try blocks.

Here is how Swift 2.0 implements the NSError in try blocks:

    lazy private var applicationSupportLogfileDirectory: String? = {

        let fileManager = NSFileManager.defaultManager()
        do {
            let applicationSupportDirectory =
                try fileManager.URLForDirectory(
                    inDomain: NSSearchPathDomainMask.UserDomainMask,
                    appropriateForURL: nil,
                    create: true).path!
            let appName = NSProcessInfo.processInfo().processName
            let dirUrl = NSURL(fileURLWithPath: applicationSupportDirectory, isDirectory: true).URLByAppendingPathComponent(appName)
            return dirUrl.URLByAppendingPathComponent("Logfiles").path

        } catch let error as NSError {
            let message: String = "Could not get application support directory, error = " + (error.localizedDescription ?? "Unknown reason")
            return nil


Or without all the verbose stuff:

        do {
            try NSFileManager.defaultManager()...some file manager call that throws an error

        } catch let error as NSError {
            print "Could not ... " + (error.localizedDescription ?? "Unknown reason")


Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment