16

I need to convert a string into an array of characters. This work in Swift 1.2 and lower but doesn't since Swift 2.0

var myString = "Hello"
Array(myString)  // ["H", "e", "l", "l", "o"]
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
Maver1ck
  • 181
  • 1
  • 1
  • 6
  • See http://stackoverflow.com/questions/25921204/convert-swift-string-to-array, which has been updated for Swift 2. – Martin R Jul 21 '15 at 22:45

3 Answers3

32
var myString = "Hello"
let characters = [Character](myString.characters)  // ["H","e","l","l","o"]

Hope this helps

Matteo Piombo
  • 6,688
  • 2
  • 25
  • 25
  • why didn't i find this a couple of days ago. much more elegant! – R Menke Jul 21 '15 at 22:48
  • nice. Might as well make it into a computed var: `extension String { var charValues : [Character] { get { guard self.isEmpty else { return [Character](self.characters) } return [] } } }` – jlmurph Jun 13 '17 at 18:56
11

First, use the characters property of String struct :

let str = "Hello World"
var charView = str.characters

You get an CharacterView instance. To access to an element of charView, you have to use String.CharacterView.Index. If you want to convert this to an array of String, do this :

let str = "Hello World"
var arr = str.characters.map { String($0) }

Now, you have an array of type [String] :

arr[0] // => "H"
Florent Bodel
  • 111
  • 1
  • 2
9

You have to use the characters property of String since it is no longer a SequenceType:

var myString = "Hello"
let charactersArray = Array(myString.characters)
Qbyte
  • 12,753
  • 4
  • 41
  • 57