Swift 3编译错误:' bytes'不可用:改为使用withUnsafeBytes

时间:2016-12-20 07:03:01

标签: 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

2 个答案:

答案 0 :(得分:3)

如错误消息所示,您需要改为使用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)
    }
}

答案 1 :(得分:-1)

试试这个

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

        //security key must be 24charachters

        var myKeyData = [UInt8]()
        var myRawData = [UInt8]()
        for char in "*******".utf8{
            myKeyData += [char]
        }
        for char in encryptData.utf8{
            myRawData += [char]
        }

        let mykeydatamd5 = Data(bytes: myKeyData, count: 24)

        let Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, mykeydatamd5.bytes   , keyLength, nil, myRawData, 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

        }
    }

希望它能帮到你