[SOLVED] Convert Swift string to array

Issue

How can I convert a String "Hello" to an Array ["H","e","l","l","o"] in Swift?

In Objective-C I have used this:

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

Solution

It is even easier in Swift:

let string : String = "Hello ๐Ÿถ๐Ÿฎ ๐Ÿ‡ฉ๐Ÿ‡ช"
let characters = Array(string)
println(characters)
// [H, e, l, l, o,  , ๐Ÿถ, ๐Ÿฎ,  , ๐Ÿ‡ฉ๐Ÿ‡ช]

This uses the facts that

  • an Array can be created from a SequenceType, and
  • String conforms to the SequenceType protocol, and its sequence generator
    enumerates the characters.

And since Swift strings have full support for Unicode, this works even with characters
outside of the โ€œBasic Multilingual Planeโ€ (such as ๐Ÿถ) and with extended grapheme
clusters (such as ๐Ÿ‡ฉ๐Ÿ‡ช, which is actually composed of two Unicode scalars).


Update: As of Swift 2, String does no longer conform to
SequenceType, but the characters property provides a sequence of the
Unicode characters:

let string = "Hello ๐Ÿถ๐Ÿฎ ๐Ÿ‡ฉ๐Ÿ‡ช"
let characters = Array(string.characters)
print(characters)

This works in Swift 3 as well.


Update: As of Swift 4, String is (again) a collection of its
Characters:

let string = "Hello ๐Ÿถ๐Ÿฎ ๐Ÿ‡ฉ๐Ÿ‡ช"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "๐Ÿถ", "๐Ÿฎ", " ", "๐Ÿ‡ฉ๐Ÿ‡ช"]

Answered By โ€“ Martin R

Answer Checked By โ€“ Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.