zlib 的 crc32 函数在 swift 中失败 3 无法使用类型为“(UnsafeRawPointer)”的参数列表调用类型 'UnsafePointer<Bytef>' 的初始值设定项
crc32 function of zlib fails in swift 3 Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)'
我想从字符串中生成 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, [=11=], numericCast(strData.count)) }
此处[=15=]
的类型自动推断为
UnsafePointer<Bytef>
来自上下文。
更新: 截至 Swift 5,
public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
使用必须“绑定”到预期类型的“原始”缓冲区指针调用闭包 Bytef
(又名 UInt8
):
let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes {
crc32(0, [=13=].bindMemory(to: Bytef.self).baseAddress, numericCast(strData.count))
}
我想从字符串中生成 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, [=11=], numericCast(strData.count)) }
此处[=15=]
的类型自动推断为
UnsafePointer<Bytef>
来自上下文。
更新: 截至 Swift 5,
public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
使用必须“绑定”到预期类型的“原始”缓冲区指针调用闭包 Bytef
(又名 UInt8
):
let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes {
crc32(0, [=13=].bindMemory(to: Bytef.self).baseAddress, numericCast(strData.count))
}