Search code examples
swifthexdecimalnsdata

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


I have code as below after converting to hex value trying to appending data object but it gives me the below error:

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)!)

Here I am trying to add b6 to data object.


Solution

  • Your use of a string to get result as a hex string is of no use just to append to returnMsg. Simply append the 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))
    

    Your crash is resulting from force-unwrapping UInt8(hexValue). Passing in the string b6 gives a nil result and the force-unwrap of nil always results in a crash and the error message you are seeing. The UInt8 initializer that takes a string only accepts a base-10 integer. You can see this in the documentation:

    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.