NSString to String throwing "fatal error: unexpectedly found nil while unwrapping an Optional value"

522 views Asked by At

The following Swift code is crashing on the return statement with the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

According to the debugger the result variable has a non-null value. I really want the function to accept Strings and return a String, not NSData. Hoping this is a dumb question and I'm just not seeing it. Been stuck on this for hours!

println(hmac_sha256("sample_data", inKey: "sample_key"))

    func hmac_sha256(inData: String, inKey: String) -> (String) {

         let data: NSData = inData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
         let key: NSData = inKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

         var result = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))

         CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key.bytes, size_t(key.length), data.bytes, size_t(data.length), result!.mutableBytes)

         return NSString(data: result!, encoding: NSUTF8StringEncoding) as! String
     }
2

There are 2 answers

0
Jeff On

Got it. I think I was missing the big picture. The goal was to convert NSData to a hex string. I found a nifty method on github for this here: https://github.com/CryptoCoinSwift/SHA256-Swift/blob/master/SHA256.swift

0
gnasher729 On

You cannot expect to be able to turn arbitrary data into an NSString with UTF-8 encoding. For example, UTF-8 can never, ever include a byte 0xff and therefore data containing that byte value can never be turned into an NSString.

So no matter how hard you want to get an NSString, you won't get it.