Since both f
and bar[42]!
point to the same closure in the following code I would expect the unsafe pointers to point to the same address.
They do not. Can anyone please explain why?
To clarify: I'm looking up the address returned by withUnsafePointer in Xcode using "view memory".
var bar = [Int : (() -> Void)]()
bar[42] = { print("foo") }
var f = bar[42]!
f() // prints "foo"
bar[42]!() // prints "foo"
withUnsafePointer(to: &f) { print( type(of: $0) ) ; print( $0 ) }
// UnsafePointer<(()) -> ()> 0x00007fff5fbff778 -> 0x100002100
withUnsafePointer(to: &bar[42]!) { print( type(of: $0) ) ; print($0) }
// UnsafePointer<(()) -> ()> 0x00007fff5fbff760 -> 0x100001d20
Update
I've updated the code to also print out the pointer's value:
var bar = [Int : (() -> Void)]()
bar[42] = { print("foo") }
var f = bar[42]!
f() // prints "foo"
bar[42]!() // prints "foo"
withUnsafePointer(to: &f) {
print( type(of: $0.pointee) )
print( $0 )
$0.withMemoryRebound(to: Int.self, capacity: 1) {
print("-> 0x\(String($0.pointee, radix: 16))")
}
}
withUnsafePointer(to: &bar[42]!) {
print( type(of: $0.pointee) )
print($0)
$0.withMemoryRebound(to: Int.self, capacity: 1) {
print("-> 0x\(String($0.pointee, radix: 16))")
}
}
Running this in Release mode gives the following output:
foo
foo
(()) -> ()
0x00007fff5fbff7d0
-> 0x100003f10
(()) -> ()
0x00007fff5fbff7d0
-> 0x100001f60
Which suggests that the compiler sees that f
and bar[42]!
are the same. What's confounding is that the same address can point to different copies of the same closure.