这是我的游乐场代码。
import Foundation
func printAddress<T>(anyObj: T,message: String = "") {
var copy = anyObj
withUnsafePointer(to: ©) {
print("\(message) value \(copy) has memory address of: \($0)")
}
}
class Account {
var balance: Int = 0
init(balance: Int) {
self.balance = balance
}
}
func deposit(amount: Int, into account: inout Account) {
account.balance += amount
printAddress(anyObj: account, message: "After deposit") //0x00007fff569ba188
printAddress(anyObj: acct,message: "Address of acct within the deposit free function") //0x00007fff59eb6188
//What makes both memory addresses are same inside the fucntion?
}
func verify(account: Account) -> Bool{
printAddress(anyObj: acct,message: "Address of acct within the verify function") //0x00007fff5a39a188
//Again surprisingly same as address used in deposit function copied account var. Optimization?
return account.balance > 0
}
var acct = Account(balance: 10)
printAddress(anyObj: acct,message:"Before deposit 20") // Print 0x00007fff518751f8
deposit(amount: 20, into: &acct)
verify(account: acct)
printAddress(anyObj: acct,message:"After and deposit and verify completed") //// Print 0x00007fff518751f8
我有2个观察结果,我不清楚。
account
(复制的实例)和acct
(原始的acct)打印相同的内存地址答案 0 :(得分:3)
发生的事情是,您始终在copy
功能中打印printAddress()
变量的地址。您不打印您传入的参数的地址,即使这是您的意图。
copy
变量的地址总是在输入printAddress()
时超过堆栈指针的某个常量固定偏移量,但是堆栈指针的变化取决于代码在{{{}时的嵌套程度。 {1}}被调用。
要查看其他值,请创建一个调用printAddress()
的函数foo()
,然后从printAddress()
调用foo()
。
同样,它始终是您在verify()
被调用的时间点看到的copy
变量的内存地址。
如果你想打印传递给print()
的东西的内存地址,你需要摆脱临时的:
printAddress()
现在打电话:
func printAddress<T>(anyObj: inout T, message: String = "") {
withUnsafePointer(to: &anyObj) {
print("\(message) value \(anyObj) has memory address of: \($0)")
}
}
从任何地方,您都会看到相同的价值。