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?
To convert an array to string in Swift, call Array. joined() function.
To join the array elements we use arr. join() method. This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,).
A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.
In the Swift array, we can count the elements of the array. To do this we use the count property of the array. This property is used to count the total number of values available in the specified array.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With