ios - Swift 3 编译器错误 : 'bytes' is unavailable: use withUnsafeBytes instead

标签 ios swift3 unsafe-pointers

我在 Swift 2.2 中有一个加密方法。如何从 Swift 3 中的数据获取字节?

这是我的代码:

func myEncrypt(encryptData:String) -> String? {

    //security key must be 24charachters 
    let myKeyData : Data = "*******".data(using: String.Encoding.utf8)!
    let myRawData : Data = encryptData.data(using: String.Encoding.utf8)!
    let mykeydatamd5 = Data(bytes: myKeyData.bytes, count: 24)
    let Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, mykeydatamd5.bytes   , keyLength, nil, myRawData.bytes, myRawData.count, buffer, buffer_size, &num_bytes_encrypted)

    if UInt32(Crypto_status) == UInt32(kCCSuccess){

        let myResult: Data = Data(bytes: buffer, count: num_bytes_encrypted)        
        free(buffer)

        return myResult.base64EncodedString()

    }else{

        free(buffer)        
        return nil

    }       
}

错误发生在 myKeyData.bytesmyRawData.bytes 中。

最佳答案

如错误消息所示,您需要改用withUnsafeBytes

一般来说,如果你有这样的表达:

let result = someFunc(..., data.bytes, ...)

您需要将其重写为:

let result = data.withUnsafeBytes {dataBytes in
    someFunc(..., dataBytes, ...)
}

如果您在单个表达式中使用多个 .bytes,则可能需要使用嵌套的 withUnsafeBytes。在您的情况下,代码的相关部分应该是这样的:

let mykeydatamd5 = myKeyData.subdata(in: 0..<24)    //Assuming myKeyData.count >= 24

let crypto_status: CCCryptorStatus = mykeydatamd5.withUnsafeBytes {mykeydataBytes in
    myRawData.withUnsafeBytes {myRawDataBytes in
         CCCrypt(operation, algoritm, options, mykeydataBytes, keyLength, nil, myRawDataBytes, myRawData.count, buffer, buffer_size, &num_bytes_encrypted)
    }
}

关于ios - Swift 3 编译器错误 : 'bytes' is unavailable: use withUnsafeBytes instead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236587/

相关文章:

Go:将 unsafe.Pointer 转换为函数指针,反之亦然

ios - 如何从 simctl 命令行检索 ios 设备屏幕分辨率

ios - CAShapeLayer 没有在 uiview 中正确居中

iterator - Swift 3 中最小的工作迭代器协议(protocol)/序列

ios - MPVolumeView AirPlay 按钮未显示

pointers - 在 Swift 中,如何确定两个 UnsafePointer 是否引用同一内存?

ios - 是否可以在 Interface Builder 中使用自动布局定位 View ,以便如果标签为空,其他 View 将不会保留空间?

ios - CGPathContainsPoint 在 iOS 12 中损坏了吗?是否有解决方法?

ios - 为什么 Collection View 中的选定单元格在 UICollection View Swift 3 中无法正确显示?

swift - 直接赋值UnsafePointer