0

I have an array that for the sake of the example can hold both Ints and Strings, so I'm calling it an array of AnyObjects.

If I have an array of Strings, and an array of Ints, how do I put those in with the existing array of AnyObjects? (To be clear I want it to be a one-level, flat array, not with nested arrays within the array or anything).

For example, this code produces an error:

var arr: [AnyObject] = []

let foo = ["one", "two"]
let bar = [1, 2]

arr += foo

The error being "Binary operator += cannot be applied to operands of type [String] and [AnyObject]".

What should I be doing here?

2 Answers 2

1

You need to set foo and bar to [AnyObject]. If you do not then swift assumes you have [String] and [Int] arrays.

var arr: [AnyObject] = []

let foo: [AnyObject] = ["one", "two"]
let bar: [AnyObject] = [1, 2]

arr += foo
arr += bar
Sign up to request clarification or add additional context in comments.

Comments

0

You need to change foo to a [AnyObject] instead of allowing it to default to [String]

let foo: [AnyObject] = ["one", "two"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.