paralaxbison
paralaxbison

Reputation: 199

How to convert Array<_Element> to array literal

I want to use an array throughout my view controller so I declare it up top. However, I want populate this array with string elements. There is an easy way to do this with one line. I'm trying not to use a for loop.

var stringArray = [String]()
...
stringArray = Array(reversedWord.characters)

What is is not letting me do is convert Array<_elements> to an array literal.

Upvotes: 0

Views: 1082

Answers (1)

Eric Aya
Eric Aya

Reputation: 70113

Your issue is that although there can be a String of one character, a single character is actually of type Character.

So when you declare an array of Strings, you can't populate this array later with Characters.

So, make an array of Character types from the beginning:

var charArray = [Character]()

This way, when you'll split a String into characters, you'll be able to add these characters to the array:

charArray += Array(reversedWord.characters)

And to convert an array of Character to an array of String, you can use map and the String() initializer:

let stringArray = charArray.map { String($0) }

Here, stringArray will be of type [String].

Upvotes: 1

Related Questions