无法为UnsafeMutablePointer <UInt8>types调用初始化程序
我试图将我的string转换为SHA256哈希,但我得到了下一个错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
这是我的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 }
所以,这部分
UnsafeMutablePointer<UInt8>(hash.mutableBytes)
我得到这个错误:
Cannot invoke initializer for type 'UnsafeMutablePointer<UInt8>' with an argument list of type '(UnsafeMutableRawPointer)'
我怎样才能解决这个问题,我做错了什么?
你最好使用Data
也为结果hash
。
在Swift 3中,使用withUnsafePointer(_:)
和withUnsafeMutablePointer(:_)
是genericstypes,当与“格式良好”的闭包一起使用时,Swift可以正确推断Pointeetypes,这意味着您不需要手动转换Pointeetypes。
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中,用于将Pointeetypes转换为Swift 2的UnsafePointer
和UnsafeMutablePointer
的初始值UnsafePointer
UnsafeMutablePointer
被删除。 但是在很多情况下,你可以在没有指针types转换的情况下工作。