What’s the simplest way to convert from a single character String to an ASCII value in Swift?

edit/update Swift 5.2 or later

extension StringProtocol {
    var asciiValues: [UInt8] { compactMap(\.asciiValue) }
}

"abc".asciiValues  // [97, 98, 99]

In Swift 5 you can use the new character properties isASCII and asciiValue

Character("a").isASCII       // true
Character("a").asciiValue    // 97

Character("รก").isASCII       // false
Character("รก").asciiValue    // nil

Old answer

You can create an extension:

Swift 4.2 or later

extension Character {
    var isAscii: Bool {
        return unicodeScalars.allSatisfy { $0.isASCII }
    }
    var ascii: UInt32? {
        return isAscii ? unicodeScalars.first?.value : nil
    }
}

extension StringProtocol {
    var asciiValues: [UInt32] {
        return compactMap { $0.ascii }
    }
}

Character("a").isAscii  // true
Character("a").ascii    // 97

Character("รก").isAscii  // false
Character("รก").ascii    // nil

"abc".asciiValues            // [97, 98, 99]
"abc".asciiValues[0]         // 97
"abc".asciiValues[1]         // 98
"abc".asciiValues[2]         // 99

Leave a Comment