Jared
Jared

Reputation: 4810

How can I convert a single Character type to uppercase?

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.

Upvotes: 7

Views: 8132

Answers (3)

Ryan H
Ryan H

Reputation: 1746

Looks like the .uppercased() method for Character was added in Swift since this question was asked, so there's no need to worry about converting it to a String or using C bridging any more.

Upvotes: 1

Nick
Nick

Reputation: 561

just add this to your program

extension Character {
    
    //converts a character to uppercase
    func convertToUpperCase() -> Character {
        if(self.isUppercase){
            return self
        }
        return Character(self.uppercased())
    }
}

Upvotes: 0

Emil Laine
Emil Laine

Reputation: 42828

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

Upvotes: 12

Related Questions