问题
According to the chapter of "Memory Safety" in the Swift Programming Language Guide (for Swift 4.2), there is a sentence "A function has long-term write access to all of its in-out parameters." https://docs.swift.org/swift-book/LanguageGuide/MemorySafety.html
I created a new command line tool project to verify it in Xcode 10.1.
var stepSize = 1
func increment(_ number: inout Int) {
print(stepSize)
}
increment(&stepSize)
I expect the output to be 1, but the actual output is a crash log "Simultaneous accesses to 0x100587430, but modification requires exclusive access."
I know this is a conflict about accessing in-out parameters, but I don't know why this happens. Why does a function have long-term write access to all of its in-out parameters?
回答1:
A consumer of this API sees func increment(_ number: inout Int)
, but not the implementation. It can only assume that increment(_:)
makes writes to the parameters, because it can, in principle.
Even if the function implementation doesn't currently do any writes, the possibility is there, so the compiler has to assume the worst case scenario. Imagine if some client code was allowed to compile against this, treating is as if it's read only (because at the time, it may be the case). What should happen to the client code when someone adds number += 1
to the function body?
This is similar to having a function that declares it can throw
, whose actual implementation doesn't throw
. The compiler still treats it as throwing, and necessitates the error be handled with some variant of try
.
来源:https://stackoverflow.com/questions/54394980/why-does-a-function-have-long-term-write-access-to-all-of-its-in-out-parameters