I wrote some functions for Swift pointers for learning and couldn’t understand the results I am getting.
The code: Questions about raw and typed pointers and generic - #3 by Luminaron
My experiments revolve around the following array:
var myIntArray = Array<Int>(repeating: 10, count: 10)
The first function gets a raw pointer, prints it and possibly does something with it:
func mutableRawPointer(to pointer: UnsafeMutableRawPointer,
_ body: (UnsafeMutableRawPointer) -> Void)
{
print("Acquired raw pointer: \(pointer)")
body(pointer)
print("Raw pointer END\n")
}
mutableRawPointer(to: &myIntArray){_ in}
Output:
Acquired raw pointer: 0x000060000390c020 // Raw Pointer Address
Raw pointer END
The second one gets a typed pointer and everything else is the same:
func arrayIntPointer(to pointer: UnsafeMutablePointer<Array<Int>>,
_ body: (UnsafeMutablePointer<Array<Int>>) -> Void)
{
print("Acquired Array<Int> typed pointer: \(pointer)")
body(pointer)
print("Array Int pointer END\n")
}
arrayIntPointer(to: &myIntArray){_ in}
Output:
Acquired Array<Int> typed pointer: 0x0000000100008038 // Typed Pointer Address
Array Int pointer END
The addresses are different!
This just confuses me. However, before I can think of a reason why. The third function brings more questions to the table. Instead of taking a specific type, the third function takes a generic type:
func genericTypedPointer<T>(to pointer: UnsafeMutablePointer<T>,
_ body: (UnsafeMutablePointer<T>) -> Void)
{
print(“Acquired generic typed pointer: \(pointer)")
body(pointer)
print("Typed generic pointer END\n")
}
genericTypedPointer(to: &myIntArray){_ in}
Output:
Acquired generic typed pointer: 0x000060000390c020 // Raw Pointer Address
Typed generic pointer END
So, I thought to myself that the issue might stem from type inference, and thus I wrote a variant of the third function with a "forced type":
func forcedTypedPointer<FT>(_ _: FT,
to pointer: UnsafeMutablePointer<FT>,
_ body: (UnsafeMutablePointer<FT>) -> Void)
{
print("Acquired forced generic pointer: \(pointer)")
body(pointer)
print("Forced generic pointer END\n")
}
forcedTypedPointer(myIntArray, to: &myIntArray){_ in}
Output:
Acquired forced generic pointer: 0x0000000100008038 // Typed Pointer Address
Forced generic pointer END
Despite these experiments, I'm left with several questions:
- Why do the memory addresses differ between typed and raw pointers for the same variable?
- Why does the generic typed pointer function behave similarly to a raw pointer function?
- In the third function, what is the type T if it's not inferred as
Array<Int>
, and why is it inferred in such a manner?