Works fine but I'm still unclear that
tmp
is not a reference to the array I want to pass?
It’s definitely not. The best way to think about
inout
is that it acts like a copy in / out operation (hence the name). You can think of this:
func test(_ a: [Int]) { … }
var b: [Int] = …
test(&b)
as being transformed to:
func test(_ a: [Int]) -> [Int] { … }
var b: [Int] = …
let tmpIn = b
let tmpOut = test(tmpIn)
b = tmpOut
Nowhere does it form a reference to the original value [1].
(which is a public var)
Of type
[AnyObject]
? Or of type
[MovieItem]
? The latter is likely to be problem because the function signature of
test
says that it can put
AnyObject
into the array; there’s no restriction that says it must work on
MovieItem
.
If you want such a restriction you should use a generic:
func test<Element>(_ toArray: inout [Element]) {
print(toArray)
}
This test that
test
works on an array of items, but that array is homogenous and the caller gets to specific the exact type.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] Except insofar as used by compiler optimisations.