The problem is the 0
after the ??
. The expression input?.cString(using: .utf8)
returns [CChar]?
so when you use ??
to provide a default if the result is nil
, you need to provide the same type of value. You need a [CChar]
but you are passing 0
which is of course an Int
.
Then for some reason you are attempting to create an Int8
from the resulting [CChar]
. That's not going to work so you need to explain why you are trying to do that.
The other consideration is that your input
parameter is optional and the return value is optional. Perhaps if input
is nil
you should just return nil
.
I would change the code you posted to:
class func computeSHA256Digest(for input: String?) -> String? {
guard let input = input else { return nil }
let cstr = input.cString(using: .utf8)!
// The rest of the code
}
The guard
simply returns nil
if input
is nil
. After the guard
there is a local variable named input
that is not optional so you can directly get its cString
value. It's safe to force-unwrap the result of cString
because you'll never get nil
with the .utf8
encoding.
At this point, cstr
is of type [CChar]
.
[CChar]
is a Array, so you can't convert Int to Array – Quoc Nguyen