Convert Swift string to array
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];
}
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 aSequenceType
, and -
String
conforms to theSequenceType
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
Character
s:
let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "🐶", "🐮", " ", "🇩🇪"]
Edit (Swift 4)
In Swift 4, you don't have to use characters
to use map()
. Just do map()
on String.
let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
Or if you'd prefer shorter: "ABC".map(String.init)
(2-bytes 😀)
Edit (Swift 2 & Swift 3)
In Swift 2 and Swift 3, You can use map()
function to characters
property.
let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
Original (Swift 1.x)
Accepted answer doesn't seem to be the best, because sequence-converted String
is not a String
sequence, but Character
:
$ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
This below works for me:
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
Reference for a global function map()
is here: http://swifter.natecook.com/func/map/