-1

Using Swift. How do I take a String and separate each character into an array?

var someString = "123"
var someArray = []

someArray[0] = "1"
someArray[1] = "2"
someArray[2] = "3"
Paul S.
  • 1,342
  • 4
  • 22
  • 43
  • possible duplicate of [Swift: Split a string into an array](http://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array) –  Oct 15 '14 at 12:08
  • possible duplicate of [Convert Swift string to array](http://stackoverflow.com/questions/25921204/convert-swift-string-to-array) – Martin R Oct 15 '14 at 12:16
  • @MrCoder: The thread that you linked to is about splitting a string into separate *words* which are separated e.g. by a space. – Martin R Oct 15 '14 at 12:17
  • @MartinR I saw your dupe straight after, but you can't highlight another 'dupe' –  Oct 15 '14 at 12:18

2 Answers2

7

Array has constructor that takes String and produce array of characters.

let someString = "abcde"
let array = Array(someString)
mustafa
  • 15,254
  • 10
  • 48
  • 57
  • 3
    More precisely, `Array` has a constructor that takes a `SequenceType`, and `String` happens to implement that protocol. Compare http://stackoverflow.com/a/25921323/1187415. – Martin R Oct 15 '14 at 12:47
1

yes there are many ways to achieve this task old and best way is to use for in loop in the following way

 var someString = "123"
    var someArray : Array<Character> = []

    for character in someString {
        someArray.append(character)
    }
    println(someArray)
Rein rPavi
  • 3,368
  • 4
  • 22
  • 32
  • I don't understand why I have been down voted the problem asked is easily solved through my code shared. – Rein rPavi Oct 15 '14 at 12:52
  • 2
    I'm not the downvoter, but I think you should explain your code. Your post currently appears in the Low Quality Posts Review Queue, so you might improve your post – msrd0 Oct 15 '14 at 13:23
  • 1
    @Pavi your post is indeed in `Low Quality Posts Review Queue`. Please provide some explanation. – Rohan Kandwal Oct 15 '14 at 13:25
  • Guys thanks for the reply in a hurry to give an answer or should I say to help the guy who posted it, I just went ahead with the code, will keep this in mind next time... – Rein rPavi Oct 15 '14 at 13:30