Why does UnsafeRawPointer show a different result when function signatures differ in Swift?

The code below can be run on Swift Playground:

import UIKit

func aaa(_ key: UnsafeRawPointer!, _ value: Any! = nil) {
    print(key)
}
func bbb(_ key: UnsafeRawPointer!) {
    print(key)
}
class A {
    var key = "aaa"
}
let a = A()
aaa(&a.key)
bbb(&a.key)

Here is the result printed on my mac:

0x00007fff5dce9248
0x00007fff5dce9220

Why are the results of the two prints different? More interestingly, when I change the signature of the bbb function to make it the same as aaa , the result of the two fingerprints is the same. And if I use the global var instead of a.key in these two function calls, the result of the two fingerprints is the same. Does anyone know why this strange behavior happens?

+6
source share
1 answer

Why are the results of the two prints different?

Swift , , a.key getter. . , , , .

, , , A key, ( ).

key , ( ).

, key final, :

class A {
    final var key = "aaa"
}

var a = A()
aaa(&a.key) // 0x0000000100a0abe0
bbb(&a.key) // 0x0000000100a0abe0

key , getter.

, . , , . , , , , , , (, , , ).

. Swift , , , . Swift C- ( ):

C- Swift, . :

  • , . , . , string , . . , : KVO.

, key A , .


bbb, aaa,

, , , -O- . .

( , Swift , Swift, , swiftc)

- , ( ). aaa, " ", , .

- A, getter a.key. a.key -, , .

, a.key , var key = arc4random(), , a.key .

, , ( ) - , , .


inout UnsafeMutable(Raw)Pointer

:

withUnsafePointer(to:_:) , ( , ), inout. , inout.

inout , UnsafeRawPointer. , inout , pointee UnsafeRawPointer.

- inout , :

  • , , getter. , , (, ) .

  • , .

, , , , final ( ). , . copy-on-write, , - .

, Swift - materializeForSet. , , , , .

- , inout - a.key materializeForSet, , , .

materializeForSet , , , UnsafeRawPointer. aaa bbb, UnsafeMutable(Raw)Pointer ( ), .

func aaa(_ key: UnsafeMutableRawPointer) {
    print(key)
}

func bbb(_ key: UnsafeMutableRawPointer) {
    print(key)
}

class A {
    var key = "aaa"
}

var a = A()

// will use materializeForSet to get a direct pointer to a.key
aaa(&a.key) // 0x0000000100b00580
bbb(&a.key) // 0x0000000100b00580

, , , , .

+4

Source: https://habr.com/ru/post/1015784/


All Articles