I just want to get the ASCII value of a single char string in Swift. This is how I\'m currently doing it:
var singleChar = \"a\"
println(singleChar.unicodeSc
You can use NSString's characterAtIndex to accomplish this...
var singleCharString = "a" as NSString
var singleCharValue = singleCharString.characterAtIndex(0)
println("The value of \(singleCharString) is \(singleCharValue)") // The value of a is 97
The way you're doing it is right. If you don't like the verbosity of the indexing, you can avoid it by cycling through the unicode scalars:
var x : UInt32 = 0
let char = "a"
for sc in char.unicodeScalars {x = sc.value; break}
You can actually omit the break
in this case, of course, since there is only one unicode scalar.
Or, convert to an Array and use Int indexing (the last resort of the desperate):
let char = "a"
let x = Array(char.unicodeScalars)[0].value
Swift 4.1
https://oleb.net/blog/2017/11/swift-4-strings/
let flags = "99_problems"
flags.unicodeScalars.map {
"\(String($0.value, radix: 16, uppercase: true))"
}
Result:
["39", "39", "5F", "70", "72", "6F", "62", "6C", "65", "6D", "73"]
Swift 4
print("c".utf8["c".utf8.startIndex])
or
let cu = "c".utf8
print(cu[cu.startIndex])
Both print 99. Works for any ASCII character.
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
There's also the UInt8(ascii: Unicode.Scalar) initializer on UInt8.
var singleChar = "a"
UInt8(ascii: singleChar.unicodeScalars[singleChar.startIndex])