0
votes

I converted an Objective-C snippet to Swift as I am migrating to Swift. I am still new to Objective-C and I have average knowledge in Swift. Having problem satisfying the argument C char trying to convert from Int8 into C Char.

class func computeSHA256Digest(for input: String?) -> String? {
    let cstr = Int8(input?.cString(using: .utf8) ?? 0)
    /* the rest of code */
}

Cannot convert value of type 'Int' to expected argument type '[CChar]' (aka Array)

1
[CChar] is a Array, so you can't convert Int to ArrayQuoc Nguyen

1 Answers

2
votes

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].