Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the equivalent of finally in Swift

I try to use the error handling modeling in Swift2.

do {
    try NSFileManager.defaultManager().removeItemAtPath("path")
} catch {
    // ...
} finally {
    // compiler error.
}

But it seems that there is no finally keyword out there.How can I achieve try-catch-finally pattern in Swift.Any help is welcome.

like image 644
tounaobun Avatar asked Jun 22 '15 07:06

tounaobun


People also ask

How do you use try catch in Swift?

try – You must use this keyword in front of the method that throws. Think of it like this: “You're trying to execute the method. catch – If the throwing method fails and raises an error, the execution will fall into this catch block. This is where you'll write code display a graceful error message to the user.

What is exception handling in Swift?

An error (exception) is an unexpected event that occurs during program execution. For example, var numerator = 10 var denominator = 0 // try to divide a number by 0 var result = numerator / denominator // error code. Here, we are trying to divide a number.

What is defer in Swift with example?

The Swift defer statement is useful for cases where we need something done — no matter what — before exiting the scope. For example, defer can be handy when cleanup actions are performed multiple times, like closing a file or locking a lock, before exiting the scope.

Is defer called after return Swift?

The defer statement is executed after the return!


3 Answers

If you are thinking about the SWIFT 2.0 error handling to be the same thing as exception you are missunderstanding.
This is not exception, this is an error that conforms to a protocol called ErrorType.
The purpose of the block is to intercept the error thrown by a throwing function or method.
Basically there is no finally, what you can do is wrap your code in a defer block, this is guaranteed to be execute and the end of the scope.
Here a sample from SWIFT 2 programming guide

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            /* Work with the file. */
        }
        // close(file) is called here, at the end of the scope.
    }
}

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. This lets you do any necessary cleanup that should be performed regardless of whether an error occurred. Examples include closing any open file descriptors and freeing any manually allocated memory.

like image 101
Andrea Avatar answered Oct 06 '22 12:10

Andrea


defer in Swift 2.0 is like a finally, that means swift ensures you to execute that defer code at the end of current function scope. Here are the some points that i need to know: 1) No matter even guard will returns 2) we can write multiple defer scopes

Here is the example and output that demonstrates multiple defers:

    func myMethod()  {
    print("Message one")
    print("Message two")
    print("Message three")
    defer {
        print("defered block 3")
    }
    defer {
        print("defered block 2")
    }
    defer {
        print("defered block 1")
    }
    print("Message four")
    print("Message five")

}
 Output:
 Message one
 Message two
 Message three
 Message four
 Message five
 defered block 1
 defered block 2
 defered block 3
like image 16
Narendra G Avatar answered Oct 06 '22 14:10

Narendra G


What you are looking for is called defer. It defines a block of code that is not executed until execution is just about to leave the current scope, but it is always executed.

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            /* Work with the file. */
        }
        // close(file) is called here, at the end of the scope.
    }
}

For more details on defer have a look at the Apple Swift documentation, especially section "Specifying Clean-up Actions".

like image 6
miho Avatar answered Oct 06 '22 14:10

miho