2

I'm trying to understand the best way to add multiple objects of different types to an [Any] array. This doesn't work in a playground in Swift 3, unless I explicitly cast the arrays and the objects in the arrays to Any.

var anyArray: [Any] = []
let strings = ["sup", "cool"]
let numbers = [5, 3]
anyArray += strings
anyArray += numbers
anyArray

It fails with the message - Cannot convert value of type '[Any]' to expected argument type 'inout _'

Alex
  • 3,861
  • 5
  • 28
  • 44
  • the inout error has to do with pointers and reference types in swift... can you post the entire method that you are trying to do this in? – MSU_Bulldog Feb 20 '17 at 15:52
  • @MSU_Bulldog this is the entirety of the code - it's in a playground. – Alex Feb 20 '17 at 15:54
  • @Alex You need to explicitly specify the type of array to `AnyObject`. `anyArray += strings as [AnyObject]` – Nirav D Feb 20 '17 at 16:00
  • The answer in the post that this was marked as a duplicate of was what I was looking for and is the correct answer to my question - thank you. – Alex Feb 20 '17 at 16:03

2 Answers2

1
    var arr = [Any]()
    let arr1:[Any] = [2,3,4]
    let arr2:[Any] = ["32","31"]
    arr += arr1
    arr += arr2
    print(arr)
Gaston Gonzalez
  • 427
  • 3
  • 6
  • So the error comes from trying to add `[Any]` and `[String]`? – BallpointBen Feb 20 '17 at 15:57
  • This is really bizzare - I've tried this and the autocomplete suggests `contentsOf:` to me, but then the compiler says 'extraneous argument label contentsOf:' - as an error so I can't even compile with this. I'm on Xcode 8.2.1 – Alex Feb 20 '17 at 15:57
  • make sure you're explicitly casting the arrays to [Any] or else the compiler will throw the "extraneous argument label" piece – Gaston Gonzalez Feb 20 '17 at 16:01
  • Once you declare the types of `arr1` and `arr2` as `[Any]`, you can do `arr += arr1` (or `anyArray += strings` in OP's example). No need for `append(contentsOf:)` – BallpointBen Feb 20 '17 at 16:03
  • made edits to match += syntax – Gaston Gonzalez Feb 20 '17 at 16:05
0

I think this is another case of useless error messages from Swift's compiler. The real issue is that AnyObject means any object (reference type); structs -- which both Int and String are -- don't count because they are value types. If you want to refer to any type at all, use Any.

BallpointBen
  • 9,406
  • 1
  • 32
  • 62
  • Ah, fair enough, but this doesn't solve the problem, the error message simply changes to be [Any] instead of [AnyObject] – Alex Feb 20 '17 at 15:55