Karthik
Karthik

Reputation: 33

How to convert a character to string in swift?

I wanted to perform a if condition for each character in a string, the string consists of digits and alphabets so I want to separate digits by using if condition, so how to extract each character and add it to another string I've tried to convert using

NSString

But even then It didn't work so is there anything like

toInt()

Upvotes: 1

Views: 2870

Answers (1)

Duyen-Hoa
Duyen-Hoa

Reputation: 15784

You can cast directly to swift String:

let c : Character = "c"
let str = String(c)

You can not access a character at a index of string with str[index], you have to access by a Range. If you want to access this way, add a subscript extension to String:

extension String {
    subscript (index: Int) -> Character {
        return self[advance(self.startIndex, index)]
    }
}

then, you can call:

let myString = "abcdef"
let c: Character  = myString[1] //return 'b'

Upvotes: 3

Related Questions