2

How can I convert a string into an array of single strings? So String -> [String]

If I do Array(myString) it results in an array of characters. I tried flatmap (or compactMap in the latest Xcode beta):

stringArray = Array(myString).flatMap { $0 as? String }

Then I get a warning: "Cast from 'Character' to unrelated type 'String' always fails" and `print(stringArray) results in [].

Is this possible?

Edit: this was already answered in a non-accepted answer in this question: Convert Swift string to array

5
  • That answer results in an array of characters, not an array of strings. Commented Mar 16, 2018 at 22:42
  • 3
    Please read also the second answer. Commented Mar 16, 2018 at 22:43
  • Yes, I see it now. Thanks. Commented Mar 16, 2018 at 22:46
  • 1
    Make sure you use map instead of flatMap Commented Mar 16, 2018 at 22:53
  • Both flatMap and map seem to work, why is the latter preferred? Commented Mar 16, 2018 at 23:41

1 Answer 1

8

You can do it like as follows... Initialize a new string inside the map.

let test = "thisIsATest"
let array = test.map( { String($0) })
Sign up to request clarification or add additional context in comments.

2 Comments

another simple method is: let anotherArray = Array(test)
that will result in an Array of Characters, whereas the question was to get Array of Strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.