10

How can I cast an array initially declared as container for Any object to an array of Strings (or any other object)? Example :

var array: [Any] = []
.
.
.
array = strings // strings is an array of Strings

I receive an error : "Cannot assign value of type Strings to type Any"

How can I do?

1
  • 2
    I think this is not possible. You can try casting strings as! [AnyObject] to use it in array reference. Commented Jan 27, 2016 at 13:13

4 Answers 4

10

You can't change the type of a variable once it has been declared, so you have to create another one, for example by safely mapping Any items to String with flatMap:

var oldArray: [Any] = []
var newArray: [String] = oldArray.flatMap { String($0) }
Sign up to request clarification or add additional context in comments.

Comments

5

Updated to Swift 5

var arrayOfAny: [Any] = []
var arrayOfStrings: [String] = arrayOfAny.compactMap { String(describing: $0) }

Comments

0

You can use this synatic sugar grammar. Still one line of code :)

var arr: [Any] = []
var strs = [String]()
arr = strs.map {$0 as! [String]}

4 Comments

In my test in playground, I didn't have to cast it to [String]. Is it really needed? And I think you mean strs.map instead of arr.map? :)
I think that question is "can compiler see arr as [String]" like you have re-declared it. Btw I haven't tested this code.
@Eendje No. you don't need cast again to [String]. I often make this for reading purpose.
This answer makes little sense. This takes an empty array of strings and tries to map each string by force-casting each string to a String array. That will fail for a couple of reasons.
-1

It can be so annoying to declare that I've resorted to declaring the data in a pList file and then simply reading it in to the variable.

You can use `contentsOfFile.

Here's a decent link to a solution: https://stackoverflow.com/a/60804155/1058199 `

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.