Last active
May 21, 2016 03:57
-
-
Save bjhomer/08b67ed78ef2cd3d83fe to your computer and use it in GitHub Desktop.
Testing whether swift captures by value or by reference.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func testCapturing() -> () { | |
var x = 3 | |
let c1 = { () -> () in | |
println( "unmodified x: \(x)") | |
} | |
let c2 = { () -> () in | |
x += 1 | |
println( "modified x: \(x)") | |
} | |
c1() // "unmodified x: 3" | |
c2() // "modified x: 4" | |
c1() // "unmodified x: 4" | |
} | |
testCapturing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The guide suggested:
“As an optimization, Swift may instead capture and store a copy of a value if that value is not mutated by a closure, and if the value is not mutated after the closure is created. Swift also handles all memory management involved in disposing of variables when they are no longer needed.”
That means without any side effect, the compiler can store a copy of value in capturing. But since c2 may mutate the value of x, the optimization won't be effective. Programmers do not need to concern the underlying memory management, we could always think it is capture-by-reference during programming. Language features never change, but implementations of compiler may be different.