gpt4 book ai didi

ios - 无法为类型 UnsafeMutablePointer 调用初始值设定项

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:26 25 4
gpt4 key购买 nike

我正在尝试将我的字符串转换为 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)'

我该如何解决这个问题以及我做错了什么?

最佳答案

对于结果 hash,您最好也使用 Data

在 Swift 3 中,withUnsafePointer(_:)withUnsafeMutablePointer(:_) 是泛型类型,Swift 可以在与“well-formed”一起使用时正确推断 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 中,UnsafePointerUnsafeMutablePointer 的初始化器被移除,它们在 Swift 2 之前用于转换 Pointee 类型。但在许多情况下,您无需对指针进行类型转换即可工作。

关于ios - 无法为类型 UnsafeMutablePointer<UInt8> 调用初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com