[英]Cannot invoke initializer for type UnsafeMutablePointer<UInt8>
I'm trying to convert my string into SHA256 hash, but I get the next error: 我正在尝试将我的字符串转换为SHA256哈希,但我得到了下一个错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
That's my function: 那是我的功能:
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
}
so, for this part 所以,对于这一部分
UnsafeMutablePointer<UInt8>(hash.mutableBytes)
I get this error: 我收到此错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
How can I fix that and what I do wrong? 我怎样才能解决这个问题以及我做错了什么?
You'd better use Data
also for the result hash
. 您最好也将Data
用于结果hash
。
In Swift 3, withUnsafePointer(_:)
and withUnsafeMutablePointer(:_)
are generic types and Swift can infer the Pointee types correctly when used with "well-formed" closures, which means you have no need to convert Pointee types manually. 在Swift 3中, withUnsafePointer(_:)
和withUnsafeMutablePointer(:_)
是泛型类型,当与“格式良好”的闭包一起使用时,Swift可以正确推断Pointee类型,这意味着您无需手动转换Pointee类型。
func withUnsafeBytes((UnsafePointer) -> ResultType) func withUnsafeBytes((UnsafePointer) - > ResultType)
func withUnsafeMutableBytes((UnsafeMutablePointer) -> 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
}
In Swift 3, the initializers of UnsafePointer
and UnsafeMutablePointer
, which was used to convert Pointee types till Swift 2, are removed. 在Swift 3中, UnsafePointer
和UnsafeMutablePointer
的初始化UnsafeMutablePointer
,用于将Pointee类型转换为Swift 2。 But in many cases, you can work without type conversions of pointers. 但在许多情况下,您可以在没有指针类型转换的情况下工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.