I'm having a big trouble using 2D array in swift. in Objective-c, I could use 2d array like below.
NSMutableArray *arrMain = [[NSMutableArray alloc] init];
NSMutableArray *arrSub = [[NSMutableArray alloc] init];
[arrMain addObject:arrSub];
[arrSub addObjects:@[@"1",@"2",@"3",@"4"]]
NSLog(@"arrayMain:%@",arrMain);
and it displayed all objects in arrSub. However, in swift it display nothing. I guess it is because of reference type. How can I append(or refer) second array like objective-c?
var arr1 = [1,2,3]
var arr2 = [arr1]
print(arr2) // [[1, 2, 3]]
arr1.append(0)
print(arr1) // [1, 2, 3, 0]
arr2.append([5,6])
print(arr2) // [[1, 2, 3], [5, 6]]
withUnsafeMutablePointer(&arr2) { (parr2) -> Void in
parr2.memory[0].append(4)
}
print(arr2) // [[1, 2, 3, 4], [5, 6]]
be careful! it is really unsafe ... you have to know exactly, what are you doing
In Objective-C,NSArray、NSMutableArray both reference type.In Swift,Array is value type. You can creat 2D array like this:
var array1 = [[Int]]() // modus 1
array1.append([10])
var array2 = Array<Array<Int>>() // modus 2
I think modus 1 is clear
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.