In my project, I'm dealing with a UInt8 buffer. Here's my code:
let bufferSize = 4096
var buffer = [UInt8](repeating: 0, count: bufferSize)
Now I need to create another buffer in UTF8 format to command and receive response for a new device, but I'm not sure how to deal with this error:
Cannot convert value of type 'Int' to expected argument type 'UTF8' (aka 'Unicode.UTF8')
let bufferSize = 4096
var buffer = [UTF8](repeating: 0, count: bufferSize)
CodePudding user response:
UTF8 is an encoding, this means a way to convert bytes into actual characters (mainly with String
class).
So when you are receiving "UTF8", it means you are actually receiving or sending bytes, which, when decoded through UTF8, are characters, or strings.
To manage bytes, you can either use [UInt8]
arrays, as mentioned, or Data
class, which is dedicated for this.
Then, you can use this to convert from [UInt8]
to String
:
let array : [UInt8] = [0x05, 0x26, 0xFD, 0xB5] // example
let data = Data(array)
let resultString = String(data: data, encoding: .utf8)
And to convert from String
to [UInt8]
:
let string = "To be converted to UTF8 bytes..."
let data = string.data(using: .utf8)!
let array = [UInt8](data)
So your first code extract is correct.
But your second is not correct. UTF8
is just an enum (?) representing the UTF8 encoding itself, not a character nor a byte in UTF8 encoding, so there is no interest in doing an [UTF8]
array.
Your output can simply be a String
. I do not think you have an expected argument to be of swift type UTF8
.