I was learning Python and wanted to confirm a certain behavior in Objective-C and Swift.
The test was as follows:
Python
def replace(list):
list[0] = 3
print(list)
aList = [1, 2, 3]
print(aList)
replace(aList)
print(aList)
Objective-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);
Swift
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))")
All the results came out as expected except for the address part in Swift. In Objective-C, the address of array remained the same in original and modified, but the print result of Swift was:
original: [1, 2, 3] address:0x00007f8ce1e092c0
array: [2, 2, 3] address:0x00007f8ce1f0c5d0
modified: [1, 2, 3] address:0x00007f8ce4800a10
Is there something I'm missing?
error: argument type '[Int]' does not conform to expected type 'AnyObject'Arrayis astruct, a value type), see the latter part of WWDC 2015 video Building Better Apps with Value Types in Swift. Note, if you want reference type behavior in Swift, useNSMutableArray(aclass), rather than theArray(astruct).