Artur Hellmann Artur Hellmann - 2 months ago 57
Swift Question

crc32 function of zlib fails in swift 3 Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)'

I want to make a CRC32 Hash out of a string and so I got the zlib function crc32.

But in Swift 3 this makes problems.

The code looks like this:

func crc32HashString(_ string: String) {
let strData = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))
}


The compiler gives me this Error:

Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)'


How do I resolve this error?

best regards and thank you for your help!

Artur

Answer

The bytes of a Data value are accessed using the

/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

method. It calls a closure with a (typed) pointer to the bytes:

let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes { crc32(0, $0, numericCast(strData.count)) }

Here the type of $0 is automatically inferred as UnsafePointer<Bytef> from the context.