You can't cast a String to an Array. They are different types, with different memory layouts.
You can initialize a String from an Array, e.g.:
let array: [UInt8] = [72, 101, 108, 108, 111]
let string = String(validating: array, as: UTF8.self)! // "Hello"
and you can initialize an Array from a String or one of its views:
let arrayOfCharacters = Array(string) // Array<Character>
let arrayOfUTF8 = Array(string.utf8) // Array<UInt8>
both of these are O(n) operations, because they have to actually copy the data (and validate/transform it, in some cases).
If you want to do string-processing-type operations on buffers without copying the data, you will likely want to follow along with @Michael_Ilseman and @glessard's proposal for string processing on contiguous storage.
Another option which may or may not be viable for you today, depending on what you're doing, is to operate on the string's .utf8
view directly, instead of on an Array
. It is a collection of bytes, and you can do many of the things that you would do with an Array
with that view directly. If you can provide some more context about what you're trying to do, we can offer some suggestions.