简体   繁体   中英

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()

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM