Home > Software design >  Swift defer behaviour
Swift defer behaviour

Time:06-28

what is the output:


var x = 5
func increment() -> Int {
defer { x  = 1 }
return x
}

x = increment()
let result = increment()
print(x, result, x)

the answer is 6 5 6,i don't know why result is 5?

CodePudding user response:

Observe that increment always returns the current value of x. This is because defer is executed after the return statement is.

After

x = increment()

x is still 5. increment returns 5, increments x to 6, then you assign the return value to x again.

After

let result = increment()

x becomes 6, and result is 5. increment returns 5 as before, increments x to 6, then you assign the return value to result.

  • Related