Inout as Any ?

Can't pass an "inout" parameter as [AnyOnject] ?


I have a func that passes back an array but then set another array as the return, wondering if I can point to that array without the middle man. The type of the in array is determined within the function.

Replies

Can't pass an "inout" parameter as [AnyOnject] ?

It would help if you explained your specific problem in more detail. The test code below shows that you can use

inout
with
[AnyObject]
, so there’s clearly more to this than you’ve explained.
func test(_ objects: inout [AnyObject]) {
    objects.append("d" as NSString)
}

var o: [AnyObject] = ["a" as NSString, "b" as NSString, "c" as NSString]
test(&o)
print(o)    // prints: [a, b, c, d]

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Sorry does need a little more info ...


func test(_ toArray: [AnyObject])

test(toArray: myArray as [AnyObject])


"Cannot convert value of type '[MovieItem]' to type '[AnyObject]' in coercion"


var tmp = myArray as [AnyObject]
test(toArray: &tmp)


Works fine but I'm still unclear that tmp is not a reference to the array I want to pass ? (which is a public var)

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.