Andrea Mario Lufino
Andrea Mario Lufino

Reputation: 7921

Swift - Array of Any to Array of Strings

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?

Upvotes: 10

Views: 12029

Answers (4)

Alex Zavatone
Alex Zavatone

Reputation: 4323

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 `

Upvotes: -1

Mike Karpenko
Mike Karpenko

Reputation: 71

Updated to Swift 5

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

Upvotes: 5

hqt
hqt

Reputation: 30276

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

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

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70098

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) }

Upvotes: 10

Related Questions