Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert [Byte]? to [Byte]

Tags:

ios

swift

Hi I'm new to swift and I'm trying to decode an array of bytes being sent back to me in form [Byte]? and when i try and use

if let string = String(bytes: d, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

It says it needs to be unwrapped. I can't change the base code which is returning the optional array as it is getting returned from a framework.

like image 612
Jordan Avatar asked Jul 15 '26 12:07

Jordan


1 Answers

Use a guard let

guard let unwrappedBytes = d else { return }

With this you will get the exact same data as before, but without the question mark.

I know it's pretty hard to understand the optional thingy in Swift. I would recommend to checkout the Apple Docs, which are pretty good: https://developer.apple.com/documentation/swift/optional

like image 56
Ling Vu Avatar answered Jul 17 '26 15:07

Ling Vu