3

In objective c it is easy to create a heterogeneous array like this:

NSArray *myArray = @["String1", "String2", 123, 456];

Is there any way to create such an array in swift?

If yes then how?

Note: I tried similar statement in swift -

var arr = ["string1", "string2", 123, 456]

but it is giving compilation error:

Playground execution failed: error: <REPL>:124:17: error: cannot convert the expression's type 'Array' to type 'IntegerLiteralConvertible'
var arr : Any = ["string1", "string2", 123, 456]

1 Answer 1

5

Yes, you can do this in Swift as well.

var arr: Array<Any> = ["string1", "string2", 123, 456]

An array of type Any can hold Strings, Ints and other objects and structs.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried this in playground but I am getting this error msg: Playground execution failed: error: <REPL>:124:11: error: cannot convert the expression's type 'Array' to type 'ArrayLiteralConvertible' var arr = ["string1", "string2", 123, 456] Any ideas?
it should work if you explicitly type it. I just edited my answer
It's worth mentioning that any time you see "it doesn't work in playground" that doesn't necessarily mean it doesn't work in Swift. Playground is very much in beta at the moment and has its issues.
My understanding is that the issue is that strings in Swift are not able to have the value nil, but AnyObjects are nil-able. Anys on the other hand do not need to be nil-able. Is that the fundamental reason?

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.