从 Int 转换为 Hex 值然后将 hex 值附加到 Data 对象后出现错误 Swift?

After converting from Int to Hex value and then Append hex value to the Data object getting error Swift?

在尝试附加数据对象后转换为十六进制值后,我有如下代码,但它给了我以下错误:

Unexpectedly found nil while unwrapping an Optional value

let n = 585
let result = 255 - n % 256 //182 is result
let hexValue = String(result, radix: 16) //b6 is result
var returnMsg = "[1,1,1, ,#00300".data(using: .utf8) as! Data
returnMsg.append(UInt8(hexValue)!)

我在这里尝试将 b6 添加到数据对象。

您使用字符串获取 result 作为十六进制字符串,仅用于附加到 returnMsg 是没有用的。只需附加 result.

let n = 585
let result = 255 - n % 256 //182 is result
var returnMsg = "[1,1,1, ,#00300".data(using: .utf8)!
returnMsg.append(UInt8(result))

您的崩溃是由于强制展开造成的 UInt8(hexValue)。传入字符串 b6 会得到 nil 结果,而 nil 的强制解包总是会导致崩溃和您看到的错误消息。采用字符串的 UInt8 初始化程序只接受以 10 为底的整数。您可以在文档中看到这一点:

The string passed as description may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9).

If description is in an invalid format, or if the value it denotes in base 10 is not representable, the result is nil.