在 Swift 3.0 中,下面的代码为 thisArray[0]
提供了不同的地址,表明该数组被深度复制。事实确实如此,还是我在分析中遗漏了什么? if let 的行为是否相同?它可能与 if let 无关,因为它是不可变的...
var thisArray: [String]? = ["One", "Two"]
withUnsafePointer(to: &thisArray![0]) {
print("thisArray[0] has address \($0)")
}
if var thisArray = thisArray {
withUnsafePointer(to: &thisArray[0]) {
print("thisArray[0] has address \($0)")
}
}
最佳答案
相关:https://developer.apple.com/swift/blog/?id=10 .
In Swift, Array, String, and Dictionary are all value types.
因此,如果您通过 var
或 let
分配现有的值类型,则会发生复制。如果您通过 var
或 let
分配现有的引用类型(例如类),那么您将分配一个引用。
关于arrays - 如果 var 似乎在 Swift 中深度复制数组。如果让?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517243/