简体   繁体   中英

Swift multidimensional array

I'm working on a piece of code that use generics. This is an example of what I'm trying to achieve :

var strings: Array<Array<String>> = [["1", "2", "3"], ["4", "5", "6"]]
var array: Array<Array<AnyObject>> = strings

But the compiler says "'String' is not identical to 'AnyObject'". I have no idea why the compiler complains and how to achieve what I need.

I already tried casting it like this :

var array: Array<Array<AnyObject>> = strings as Array<Array<AnyObject>>

Without any success.

Do you guys have any idea ?

Thanks.

That doesn't work because, as the compiler says, AnyObject is not String , although you can cast AnyObject to String and vice versa.

It doesn't even work using different value types that may seem "compatible":

var array1: Array<Array<UInt>> = []
var array2: Array<Array<Int>> = array1

The only way to do what you need is to write a converter that given an array containing object of type String returns an array of AnyObject .

The reason is that even if 2 data types are compatible, they do not use the same amount of memory and can have different data members and initialization constraints.

Taking into account that arrays are value types, the assignment is not done by reference - instead a copy of the array is created and assigned to the destination variable. If the underlying data type is the same for left and right side of the assignment, each item in the array can just be copied byte by byte to create a copy of it. If the left and right side have different types, that is not possible because most likely they use memory in a different way (ie they may have different data members), so in that case the object should be instantiated via an initializer, but which one and using which parameters?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM