Swift - Array of Any to Array of Strings
Updated to Swift 5
var arrayOfAny: [Any] = []
var arrayOfStrings: [String] = arrayOfAny.compactMap { String(describing: $0) }
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) }
You can use this synatic sugar grammar. Still one line of code :)
var arr: [Any] = []
var strs = [String]()
arr = strs.map {$0 as! [String]}