C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: It changes the first value in the byte array. It increments it, changing "p" to "q."
String: Finally the program uses an "if let" statement to create a String from the byte array. It specifies ASCII encoding.
Swift program that converts string to byte array
import Foundation
// An input string.
let name = "Codex"
// Get the String.UTF8View.
let bytes = name.utf8
print(bytes)
// Get an array from the UTF8View.
// ... This is a byte array of character data.
var buffer = [UInt8](bytes)
// Change the first byte in the byte array.
// ... The byte array is mutable.
buffer[0] = buffer[0] + UInt8(1)
print(buffer)
// Get a string from the byte array.
if let result = String(bytes: buffer, encoding: NSASCIIStringEncoding) {
print(result)
}
Output
Codex
[113, 101, 114, 108, 115]
qerls
Here: We create an empty byte array (with the UInt8 type). We add 3 UInt8 values to the array.
Result: Our resulting string has the value "abc" from the bytes added to the buffer. We use ASCII encoding.
Swift program that creates string from bytes
import Foundation
// An empty UInt8 byte array.
var buffer = [UInt8]()
// Add some bytes to the byte array.
buffer.append(UInt8(97))
buffer.append(UInt8(98))
buffer.append(UInt8(99))
// Get a string from the byte array.
if let result = String(bytes: buffer, encoding: NSASCIIStringEncoding) {
print(result)
}
Output
abc