Swift - Array of Any to Array of Strings
Asked Answered
C

4

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?

Conover answered 27/1, 2016 at 13:9 Comment(1)
I think this is not possible. You can try casting strings as! [AnyObject] to use it in array reference.Hydrobomb
B
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) }
Brightwork answered 27/1, 2016 at 13:16 Comment(0)
E
5

Updated to Swift 5

var arrayOfAny: [Any] = []
var arrayOfStrings: [String] = arrayOfAny.compactMap { String(describing: $0) }
Epicarp answered 27/8, 2020 at 13:58 Comment(0)
H
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]}
Hensley answered 27/1, 2016 at 13:21 Comment(4)
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? :)Stricture
I think that question is "can compiler see arr as [String]" like you have re-declared it. Btw I haven't tested this code.Hydrobomb
@Stricture No. you don't need cast again to [String]. I often make this for reading purpose.Hensley
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.Plover
T
-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://mcmap.net/q/1164167/-swift-5-how-to-read-variables-in-plist-files `

Tuxedo answered 23/10, 2023 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.