Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Andrea Mario Lufino Avatar asked Jan 27 '16 13:01

Andrea Mario Lufino


People also ask

How do I convert an array to a string in Swift?

To convert an array to string in Swift, call Array. joined() function.

How can you put all the elements of an array in a string?

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(,).

What is string any in Swift?

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.

How do you count occurrences of an element in a Swift array?

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.


2 Answers

Updated to Swift 5

var arrayOfAny: [Any] = []
var arrayOfStrings: [String] = arrayOfAny.compactMap { String(describing: $0) }
like image 153
Mike Karpenko Avatar answered Oct 07 '22 23:10

Mike Karpenko


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) }
like image 28
Eric Aya Avatar answered Oct 07 '22 22:10

Eric Aya