Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active September 6, 2022 23:19
Show Gist options
  • Save JadenGeller/be9a6d13421a65583d7c to your computer and use it in GitHub Desktop.
Save JadenGeller/be9a6d13421a65583d7c to your computer and use it in GitHub Desktop.
Inout is really UnsafeMutablePointer!
var a = 0
var b = 0
// UnsafeMutablePointer definition
func test2(x: UnsafeMutablePointer<Int>) {
x.memory += 1
// We have to manually dereference x within this method
}
// Inout definition
func test(inout x: Int) {
x += 1
// Inout works like C++ references, no need for an explicit dereference
// (Note that it is still way less gross than C++ because you still need to use & to pass the pointer in on call in Swift)
}
// We call them both the EXACT SAME WAY
test(&a)
test2(&b)
println(a) // -> 1
println(b) // -> 1
// Same result!
// We could make a function that returns an UnsafeMutablePointer from a Swift variable like so:
func makePointer<T>(x: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T> {
return x
}
let pointerToA = makePointer(&a)
@danielchasehooper
Copy link

danielchasehooper commented Jul 25, 2016

The calling syntax may be the same, but the semantics are slightly different. Here is an explanation from someone on stack overflow, (if you change inout in the below example to UnsafeMutablePointer the program will have undefined behavior):

Normally, in-out parameter is passed by reference, but it's just a result of compiler optimization. When a closure captures an inout parameter, "pass-by-reference" is not safe, because the compiler cannot guarantee the lifetime of the original value. For example, consider the following code:

func foo() -> () -> Void {
    var i = 0
    return bar(&i)
}

func bar(inout x:Int) -> () -> Void {
    return {
        x++
        return
    }
}

let closure = foo()
closure()

In this code, var i is freed when foo() returns. If x is a reference to i, x++ causes access violation. To prevent that situation, Swift adopts "call-by-copy-restore" strategy here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment