Swift Converting Character to String

How about the simple String(theCharacter)

Works in Swift 4 and Swift 5


Your problem is quite simple: your characterAtIndex function returns a Character, and self.titleLabel.text is a String. You can't convert between the two implicitly. The easiest way would be to turn the Character into a String using the String initialiser:

// ch will be Character? type.
if let ch = str.characterAtIndex(3) {
    // Initialise a new String containing the single character 'ch'
    harfim.getLetter(String(ch))
} else {
    // str didn't have a third character.
}

Unlike other solutions, this is safe for unusual Unicode characters, and won't initialise a potentially large array or iterate the whole String just to get the third character.


Change this:

var bufi=str.characterAtIndex(3)
harfim.getLetter(bufi as AnyObject)

to this:

harfim.getLetter(String(Array(str)[3]))

So what happening here:

  1. we create an array from our string. Array elements are symbols from original string. Such break down correctly tracks symbols that are presented with a sequences of two or more code points. E.g. emoji or flag as noted by @MartinR.

  2. We access element at 4-th position.

Note that as we crate an array from initial string then performance wise is better to use this method only with short strings and avoid it in oft-repeated routines. But in your case it seems to be OK.

Tags:

Ios

Swift