All I want to do is convert a single Character
to uppercase without the overhead of converting to a String
and then calling .uppercased()
. Is there any built-in way to do this, or a way for me to call the toupper()
function from C without any bridging? I really don't think I should have to go out of my way for something so simple.
答案 0 :(得分:10)
To call the C toupper()
you need to get the Unicode code point of the Character
. But Character
has no method for getting its code point (a Character
may consist of multiple code points), so you have to convert the Character
into a String
to obtain any of its code points.
So you really have to convert to String
to get anywhere. Unless you store the character as a UnicodeScalar
instead of a Character
. In this case you can do this:
assert(unicodeScalar.isASCII) // toupper argument must be "representable as an unsigned char"
let uppercase = UnicodeScalar(toupper(CInt(unicodeScalar.value)))
But this isn't really more readable than simply using String
:
let uppercase = Character(String(character).uppercased())
答案 1 :(得分:0)
只需将其添加到您的程序中
extension Character {
//converts a character to uppercase
func convertToUpperCase() -> Character {
if(self.isUppercase){
return self
}
return Character(self.uppercased())
}
}