Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift language interview question about defer behavior

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading