Skip to content

Instantly share code, notes, and snippets.

@joaoduartemariucio
Last active September 29, 2021 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaoduartemariucio/4607c4b86cd9525e93ee34bd65572739 to your computer and use it in GitHub Desktop.
Save joaoduartemariucio/4607c4b86cd9525e93ee34bd65572739 to your computer and use it in GitHub Desktop.
String to Decimal ASCII value
import Foundation
// Converting a letter to decimal
// Manual form
let lowercaseA: UInt8? = Character("a").asciiValue
print("decimal ascii: \(lowercaseA)")
// OUTPUT
// decimal ascii: 97
let uppercaseA: UInt8? = Character("a").asciiValue
print("decimal ascii: \(uppercaseA)")
// OUTPUT
// decimal ascii: 65
// Using an extension
extension String {
var asciiValue: UInt8? { Character(self).asciiValue }
}
let lowercaseA2 = "a".asciiValue
print("decimal ascii: \(lowercaseA2)")
// OUTPUT
// decimal ascii: 97
// Converting a Phrase to a Decimal Array
extension StringProtocol {
var asciiValues: [UInt8] { compactMap(\.asciiValue) }
}
let decimalArray = "joao vitor".asciiValues
print("decimal ascii array: \(decimalArray)")
// OUTPUT
// decimal ascii array: [106, 111, 97, 111, 32, 118, 105, 116, 111, 114]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment