split a string into an array of characters in swift

To split a string into an array of characters in Swift, you can use the map() function to transform each character in the string into an element in the array:

main.swift
let str = "Hello, World!"
let chars = str.map { $0 }
print(chars) // ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
135 chars
4 lines

Alternatively, you can use the Array() initializer to create an array of characters from the string:

main.swift
let chars = Array(str)
print(chars) // ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
105 chars
3 lines

Both approaches work well to split a string into an array of characters in Swift.

gistlibby LogSnag