Swift多维数组 [英] Swift multidimensional array
问题描述
我正在研究一些使用泛型的代码。这是我试图实现的一个例子:
var strings:Array< Array< String>> = [[1,2,3],[4,5,6]]
var array:Array< Array< AnyObject>> =字符串
但是编译器说'String'与'AnyObject'不相同。
我不知道为什么编译器会抱怨以及如何实现我所需要的。
我已经试过像这样投射它:
var array:Array< Array< AnyObject>> = strings as Array< Array< AnyObject>>
没有任何成功。
你你们有什么想法吗?
谢谢。
因为,正如编译器所说, AnyObject
不是 字符串
,尽管您可以将 AnyObject
转换为字符串
,反之亦然。
甚至没有使用可能看起来兼容的不同值类型:
var array1:Array< Array< UInt>>> ; = []
var array2:Array< Array< Int>> = array1
完成所需的唯一方法是编写一个转换器,给定一个包含对象 String
返回一个 AnyObject
。
原因是,即使两种数据类型兼容,它们也不会使用相同数量的内存,并且可能具有不同的数据成员和初始化限制。
考虑到数组是值类型,赋值不是通过引用完成的 - 而是创建数组的副本并将其分配给目标变量。如果基础数据类型对于赋值的左侧和右侧是相同的,则可以将数组中的每个项目逐个字节地复制以创建它的副本。如果左侧和右侧具有不同的类型,那是不可能的,因为它们很可能以不同的方式使用内存(即它们可能具有不同的数据成员),所以在这种情况下,对象应该通过初始化器实例化,但是哪一个并使用哪些参数?
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 (i.e. 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?
这篇关于Swift多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!