Code Snippet: Characters and Strings to ASCII Values

From Coder Merlin
Revision as of 16:43, 10 December 2018 by Chukwuemeka-tinashe (talk | contribs) (Created page with "== Characters and Strings to ASCII Values == <syntaxhighlight lang="swift"> // Credit: // https://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-f...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Characters and Strings to ASCII Values[edit]

// Credit: 
//     https://stackoverflow.com/questions/29835242/whats-the-simplest-way-to-convert-from-a-single-character-string-to-an-ascii-va
//     https://stackoverflow.com/users/2303865/leo-dabus

// First, set up required extension for Character
extension Character {
    var isAscii: Bool {
        return unicodeScalars.first?.isASCII == true
    }
    var ascii: UInt32? {
        return isAscii ? unicodeScalars.first?.value : nil
    }
}

// Then, set up useful extension for Strings
extension StringProtocol {
    var ascii: [UInt32] {
        return compactMap { $0.ascii }
    }
}

// Demonstrate obtaining the value for a single character
print("H".ascii)

// Demonstrate obtaining the value for a string
print("Hello".ascii)