C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
UnicodeScalar: We convert the value 97 to a UnicodeScalar instance with an init method. We then create a Character from that.
Result: We find that the value 97 was converted into a Character that indicates a lowercase letter "a."
Swift program that converts Int to Character
let value = 97
// Convert Int to a UnicodeScalar.
let u = UnicodeScalar(value)
// Convert UnicodeScalar to a Character.
let char = Character(u)
// Write results.
print(char)
Output
a
Utf16: This returns UInt16 values. We can convert these to an Int or cast them with no errors.
Utf8: This returns UInt8 chars. It is important that the string not contain non-ASCII characters when we use this.
Swift program that converts string characters to Ints
let value = "abc"
for u in value.utf16 {
// This value is a UInt16.
print(u)
}
print("") // Write newline.
for u in value.utf8 {
// This value is a UInt8.
print(u)
}
Output
97
98
99
97
98
99