简体   繁体   中英

Swift array of different types

As I know array is value type in Swift, there are no references.

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. How is it possible to get the third element without iteration?

As I know array is value type in Swift, there are no references.

The second half is incorrect. A type T being a value type just means that this code prints "1, 2", instead of "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. This does not make Array a "non-value type", because the whole array is still copied when you reassign variables of type [Any] . Another, possibly more convincing reason, is that the entire value of the array is still stored in 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.

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

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