我想从字符串中生成 CRC32 哈希,因此我得到了 zlib 函数 crc32。
但是在 Swift 3 中这会产生问题。
代码如下所示:
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))
}
编译器给我这个错误:
Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)'
如何解决此错误?
谨致问候并感谢您的帮助!
阿图尔
最佳答案
Data
的字节数使用
/// 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
方法。它使用指向字节的(类型化)指针调用闭包:
let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes { crc32(0, $0, numericCast(strData.count)) }
这里的类型是 $0
自动推断为
UnsafePointer<Bytef>
从上下文来看。
更新:从 Swift 5 开始,
public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
使用“原始”缓冲区指针调用闭包,该指针必须“绑定(bind)”到预期类型 Bytef
(又名 UInt8
):
let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes {
crc32(0, $0.bindMemory(to: Bytef.self).baseAddress, numericCast(strData.count))
}
关于swift - zlib 的 crc32 函数在 swift 3 中失败无法使用类型 'UnsafePointer<Bytef>' 的参数列表调用类型 '(UnsafeRawPointer)' 的初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725022/