我正在學習Python並希望確認Objective-C和Swift中的特定行爲。當涉及到相同的變量時,Swift Array內存地址發生變化
試驗如下:
的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
相同,但斯威夫特的打印結果爲:
original: [1, 2, 3] address:0x00007f8ce1e092c0
array: [2, 2, 3] address:0x00007f8ce1f0c5d0
modified: [1, 2, 3] address:0x00007f8ce4800a10
有我丟失的東西?
unsafeAddressOf(數字)不起作用。這裏是錯誤:'錯誤:參數類型'[Int]'不符合期望的類型'AnyObject'' – BridgeTheGap
這可能是一個Xcode版本的東西(它在Xcode 7.2中起作用)。無論如何,我的觀察是,如果你對後面的一些細節感興趣,當你改變一個值類型(而'Array'是一個'struct',一個值類型)時,請參閱後面的部分WWDC 2015視頻[在Swift中使用值類型構建更好的應用程序](https://developer.apple.com/videos/play/wwdc2015-414/)。注意,如果你想在Swift中引用類型行爲,使用'NSMutableArray'(一個'''''',而不是'''''''struct'')。 – Rob