ParalaxWobat ParalaxWobat - 1 year ago 113
Swift Question

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.

Answer Source

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 = { String($0) }

Here, stringArray will be of type [String].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download