3

I’ve always been wondering how Swift’s [Any] arrays work internally. E.g.

struct Dog {
    let name: String
    let age: Int
}

struct Foo {
    let a: String
    let b: Int
    let c: Int
}

func test() -> [Any] {
    let s = [Dog(name: "James", age: 23), Foo(a: "abc", b: 2, c: 2)] as [Any]
    return s
}

print(test()[0])

Does Swift simply allocate an array of pointers and copy the structs into the heap? Or is there some other kind of magic going on? Does it bridge the array to NSArray?

idmean
  • 14,540
  • 9
  • 54
  • 83
  • 7
    Watch https://developer.apple.com/videos/play/wwdc2016/416/ :) – Martin R Jan 04 '17 at 11:40
  • @MartinR Thanks, I definitely will! – idmean Jan 04 '17 at 11:41
  • This answer http://stackoverflow.com/a/38387367/1187415 also contains information relavant to your question: *"The box is of a known size, and it may have to heap-allocate the thing it points to (or maybe not; depends), ..."* – Martin R Jan 04 '17 at 12:23
  • Also related: http://stackoverflow.com/questions/38332616/at-runtime-how-does-swift-know-which-implementation-to-use. – Martin R Jan 04 '17 at 12:39

0 Answers0