我试图将我的字符串转换为SHA256哈希,但是我收到了下一个错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
这是我的职责:
func SHA256(data: String) -> Data {
var hash = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))!
if let newData: Data = data.data(using: .utf8) {
let bytes = newData.withUnsafeBytes {(bytes: UnsafePointer<CChar>) -> Void in
CC_SHA256(bytes, CC_LONG(newData.length), UnsafeMutablePointer<UInt8>(hash.mutableBytes))
}
}
return hash as Data
}
所以,对于这部分
UnsafeMutablePointer<UInt8>(hash.mutableBytes)
我收到此错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
我该如何解决这个问题以及我做错了什么?
答案 0 :(得分:2)
您最好还使用Data
作为结果hash
。
在Swift 3中,withUnsafePointer(_:)
和withUnsafeMutablePointer(:_)
是泛型类型,当与“格式良好”的闭包一起使用时,Swift可以正确推断Pointee类型,这意味着您无需手动转换Pointee类型
func withUnsafeBytes((UnsafePointer) -> ResultType)
func withUnsafeMutableBytes((UnsafeMutablePointer) -> ResultType)
func SHA256(data: String) -> Data {
var hash = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
if let newData: Data = data.data(using: .utf8) {
_ = hash.withUnsafeMutableBytes {mutableBytes in
newData.withUnsafeBytes {bytes in
CC_SHA256(bytes, CC_LONG(newData.count), mutableBytes)
}
}
}
return hash
}
在Swift 3中,删除了用于将Pointee类型转换为Swift 2的UnsafePointer
和UnsafeMutablePointer
的初始值设定项。但在许多情况下,您可以在没有指针类型转换的情况下工作。