String
, byte
arrayIn Swift 5.9 a byte
is called a UInt8
—an unsigned 8 bit integer. A byte
array is a UInt8
array. In ASCII we can treat chars as UInt8
values.
With the utf8 String
property, we get a UTF8View
collection. We can convert this to a byte
array. Then we can manipulate bytes. We can convert those bytes into a String
.
This example takes a String
with value "PERLS" and gets its UTF8View
. Then it creates a byte
array from the UTF8View
with an array creation statement.
byte
array. It increments it, changing "P" to "Q."String
from the byte
array. It specifies ASCII encoding.import Foundation // An input string. let name = "PERLS" // 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: String.Encoding.ascii) { print(result) }PERLS [81, 69, 82, 76, 83] QERLS
string
, bytesIt is possible to create a String
from a sequence of bytes. We can specify these directly in the program. This allows dynamic creation of strings.
byte
array (with the UInt8
type). We add 3 UInt8
values to the array.string
has the value "abc" from the bytes added to the buffer. We use ASCII encoding.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: String.Encoding.ascii) { print(result) }abc
In Swift, Strings are hard to manipulate. Using a UInt8
array to create certain kinds of strings (like those meant for machines) is a good strategy to improve performance and gain clarity.
In Swift we have access to a utf8 property. This is key to converting Strings to byte
arrays. We use the UInt8
type to indicate a byte
in this language.