我正在学习Python并希望确认Objective-C和Swift中的某种行为。
测试如下:
的Python
def replace(list):
list[0] = 3
print(list)
aList = [1, 2, 3]
print(aList)
replace(aList)
print(aList)
目标C
- (void)replace:(NSMutableArray *)array {
array[0] = @1;
NSLog(@"array: %@, address: %p\n%lx", array, array, (long)&array);
}
NSMutableArray *array = [@[@1, @2, @3] mutableCopy];
NSLog(@"original: %@, address: %p \n%lx", array, array, (long)&array);
[self replace:array];
NSLog(@"modified: %@, address: %p \n%lx", array, array, (long)&array);
夫特
var numbers = [1, 2, 3]
let replace = { (var array:[Int]) -> Void in
array[0] = 2
print("array: \(array) address:\(unsafeAddressOf(array as! AnyObject))")
}
print("original: \(numbers) address:\(unsafeAddressOf(numbers as! AnyObject))")
replace(numbers)
print("modified: \(numbers) address:\(unsafeAddressOf(numbers as! AnyObject))")
除Swift中的地址部分外,所有结果都按预期显示。在Objective-C中,数组的地址在original
和modified
中保持不变,但Swift的打印结果是:
original: [1, 2, 3] address:0x00007f8ce1e092c0
array: [2, 2, 3] address:0x00007f8ce1f0c5d0
modified: [1, 2, 3] address:0x00007f8ce4800a10
我有什么遗失的吗?
答案 0 :(得分:5)
Swift中的数组具有值语义,而不是Python和Objective-C中数组的引用语义。您看到不同地址(以及地址)的原因是,每次执行as! AnyObject
演员表时,您实际上都在告诉Swift将Array<Int>
结构桥接到{{1}的实例}}。由于你连接了三次,你会得到三个不同的地址。
你不应该考虑Swift数组的地址,但是如果你想(暂时)获取数组缓冲区的地址,你可以这样做:
NSArray
这使您可以看到缓冲区的写时复制:
func getBufferAddress<T>(array: [T]) -> String {
return array.withUnsafeBufferPointer { buffer in
return String(buffer.baseAddress)
}
}