Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defer in function didn't work in Swift 2.0

Im testing Swift 2.0 and the new keyword defer in a Playground:

func branch() -> String {

    var str = ""

    defer { str += "xxx" }
    str += "1"

    let counter = 3;

    if counter > 0 {
        str += "2"
        defer { str += "yyy" }
        str += "3"
    }      
    str += "4"

    return str    
}

let bran = branch()

I expected bran to be "123yyy4xxx", but it actually is "123yyy4"

Why did my defer (str += "xxx") not work as expected?

like image 872
Vic Avatar asked Jan 20 '16 08:01

Vic


People also ask

How do I use defer in Swift?

With the setNeedsLayout() method, we can use defer to update the view. It may be necessary to call this method multiple times. By using defer , there's no worry about forgetting to execute the setNeedsLayout() method. defer will ensure that the method is always executed before exiting the scope.

Is defer called after return Swift?

The Swift defer statement allows you to execute code right before scope is exited (for example, before a function returns).

Does defer block?

You use a defer statement to execute a set of statements just before code execution leaves the current block of code. The block of code might be a method, an if statement, a do block or a loop. The body of the defer statement runs regardless of how you leave the block, including throwing an error.

What is defer keyword?

In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns. In simple words, defer will move the execution of the statement to the very end inside a function.


1 Answers

A defer statement defers execution until the current scope is exited.

That what apple says. So the defer statement will be executed after return statement. That's why you cannot see the expected result.

like image 83
Greg Avatar answered Sep 24 '22 10:09

Greg