Swift-Interview-questions icon indicating copy to clipboard operation
Swift-Interview-questions copied to clipboard

值类型被赋予给一个变量、常量或者被传递给一个函数的时候,其值会被拷贝

Open JackMayx opened this issue 4 years ago • 1 comments

这一句明显有问题:这个需要分情况 例如: var aLists = [1,2,3,4,5] var bLists = aLists

这种情况下,将aLists赋值给变量bLists,list并不会被拷贝,而是aLists和bLists共同用一块内存。

如果下面: bLists.append(6) 那么这样才会有两份不同的List。

JackMayx avatar Jul 16 '20 09:07 JackMayx

var aLists = [1,2,3,4,5] var bLists = aLists

print(String.init(format: "aLists == %p", aLists)) print(String.init(format: "bLists == %p", bLists))

bLists.append(6) print("添加后") print(String.init(format: "bLists == %p", bLists))

+++Log aLists == 0x600001c8bee0 bLists == 0x600001c8bf00 添加后 bLists == 0x600001c85c20

可查看 https://swiftgg.gitbook.io/swift/swift-jiao-cheng/09_structures_and_classes#structures-and-enumerations-are-value-types

zlfyuan avatar Jul 16 '20 10:07 zlfyuan