5
var password : string = "F36fjueEA5lo903"

i need separte this character by character.

something like this.

var 1character : string = "F"
var 2character : string = "3"
var 3character : string = "6"

. . .

PD: I am a novice

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • While you can convert the string to an array of characters, it’s worth asking the question “what are you trying to do?”. Often, iterating over the string using map, find, slicing etc gets you what you need without having to do that conversion. – Airspeed Velocity Apr 28 '15 at 23:34
  • Compare http://stackoverflow.com/questions/25921204/convert-swift-string-to-array – Martin R Apr 29 '15 at 01:28

2 Answers2

6

You can do it with:

let characters = Array(password)

With this you have an array of the characters in the String. You can assign it to other variables if you want to.

Eendje
  • 8,815
  • 1
  • 29
  • 31
1

While you can do it like Jacobson showed you in his answer(perfectly fine), you shouldn't save the letters manually in own variables. Because you often don't know the length of the password. So what you could do is iterating over your chars:

for letter in yourString{
    //do something with the current letter
    var yourCurrentLetter = letter
    println(yourCurrentLetter)//a then s, d, f etc.
}
Christian
  • 22,585
  • 9
  • 80
  • 106
  • Well, yea I said you can assign it to other variables purely because it's unknown what he wants to do with it ;p – Eendje Apr 28 '15 at 23:40
  • @JacobsonTalom Your answer is perfectly fine.(+1 from me) But most of the time if the OP is a beginner, they don't know about the possibilities to make things more simple. – Christian Apr 28 '15 at 23:41
  • True, I was thinking of adding some examples with `map`, but I think your example with a `for-loop` would be easier to understand. On the other hand, I thought arrays are one of the first basic things a beginner would learn, hence why I showed him how to make an array :) (and thanks) – Eendje Apr 28 '15 at 23:44
  • If you want to `for…in` over the string, there’s no need to convert it to an array first, strings conform to `SequenceType` too. – Airspeed Velocity Apr 28 '15 at 23:49
  • np - I agree with you that chances are the questioner doesn’t really need “the third character”, they need to achieve some other goal and chances are `for…in` or `map` or `find` etc will do the trick – Airspeed Velocity Apr 28 '15 at 23:57