简体   繁体   English

不同类型的 Swift 数组

[英]Swift array of different types

As I know array is value type in Swift, there are no references.据我所知,数组是 Swift 中的值类型,没有引用。

Could you please explain me the following situation:能否请您解释一下以下情况:

var arr: [Any] = [1, "1", UIView(), "qwerty"]
print(arr[3] as! String)

How is "arr[3]" O(1) operation. "arr[3]" O(1) 操作如何。 How is it possible to get the third element without iteration?如何在没有迭代的情况下获得第三个元素?

As I know array is value type in Swift, there are no references.据我所知,数组是 Swift 中的值类型,没有引用。

The second half is incorrect.下半场不正确。 A type T being a value type just means that this code prints "1, 2", instead of "2, 2":作为值类型的类型T仅意味着此代码打印“1, 2”,而不是“2, 2”:

var a = T()
a.someIntProperty = 1
var b = a
b.someIntProperty = 2
print("\(a.someIntProperty), \(b.someIntProperty)")

Being a value/reference type implies a set of behaviours, not how the type is implemented under the hood.作为一个值/引用类型意味着一组行为,而不是该类型是如何在幕后实现的。

As you said, for the array accesses to work at O(1) time, the array will need to contain pointers to the elements of the array, which are all of the same size.正如您所说,要使数组访问在 O(1) 时间工作,数组将需要包含指向数组元素的指针,这些元素的大小都相同。 This does not make Array a "non-value type", because the whole array is still copied when you reassign variables of type [Any] .这不会使Array成为“非值类型”,因为当您重新分配[Any]类型的变量时,仍会复制整个数组。 Another, possibly more convincing reason, is that the entire value of the array is still stored in arr .另一个可能更有说服力的原因是数组的整个值仍然存储在arr It's just that it's a bunch of pointers to the elements.只是它是一堆指向元素的指针。 If Array truly were a reference type, arr would store one pointer, pointing to the value of the array.如果Array确实是一种引用类型,则arr将存储一个指针,指向数组的值。

数组按顺序存储在内存中的块中,因此对于索引,它是一个O(2)的计算,它指的是指向实际数据内容的指针,最有可能只使用Any ,其中每个元素的大小不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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