Unichar variable in Swift

3.6k views Asked by At

How to define a unichar type variable in Swift likes '\0' '\n' in Objective-C ?

In Swift,

func previousCharacter() -> unichar {
    return "\n"     //Error
}

Compiler gave me an error:

Cannot convert return expression of type 'String' to expected return type 'unichar'

But in Objective-C, it will more easy to do this directly.

1

There are 1 answers

5
Sulthan On BEST ANSWER

In Swift, the character literals are of type Character.

let exclamationMark: Character = "!"

See Strings and Characters

For advanced readers:

You can also extend unichar with the capability to accept character literals:

extension unichar : UnicodeScalarLiteralConvertible {
    public typealias UnicodeScalarLiteralType = UnicodeScalar

    public init(unicodeScalarLiteral scalar: UnicodeScalar) {
        self.init(scalar.value)
    }
}


let newLine: unichar = "\n"
let whitespaces = NSCharacterSet.whitespaceAndNewlineCharacterSet()

print("C is whitespace \(whitespaces.characterIsMember(newLine))")

However, note that Swift literals use 4 bytes while unichar uses only 2 bytes, therefore some characters will be truncated when converted to unichar.