将 UnsafeMutablePointers 转换为 UnsafeMutableRawPointers

Casting UnsafeMutablePointers to UnsafeMutableRawPointers

我在更新到 swift 3.0 时遇到了一些问题。我有以下代码:

  // Retrieve the Device GUID
        let device = UIDevice.current
        let uuid = device.identifierForVendor
        let mutableData = NSMutableData(length: 16)
        (uuid! as NSUUID).getBytes(UnsafeMutablePointer(mutableData!.mutableBytes))

        // Verify the hash
        var hash = Array<UInt8>(repeating: 0, count: 20)
        var ctx = SHA_CTX()
        SHA1_Init(&ctx)
        SHA1_Update(&ctx, mutableData!.bytes, mutableData!.length)
        SHA1_Update(&ctx, (opaqueData1! as NSData).bytes, opaqueData1!.count)
        SHA1_Update(&ctx, (bundleIdData1! as NSData).bytes, bundleIdData1!.count)
        SHA1_Final(&hash, &ctx)
        let computedHashData1 = Data(bytes: UnsafePointer(&hash), count: 20)

我的第一个问题是代码行:

(uuid! as NSUUID).getBytes(UnsafeMutablePointer(mutableData!.mutableBytes))

mutableData!.mutableBytes 现在 returns 一个 UnsafeMutableRawPointer 并且编译器抱怨 "cannot invoke initializer for type 'UnsafeMutablePointer<_> with an argument of type '(UnsafeMutableRawPointer)'" 现在我一直试图将它们转换为相同的类型但没有成功。

我的第二个问题是:

let computedHashData1 = Data(bytes: UnsafePointer(&hash), count: 20)

此行导致编译器错误"Ambiguous use of 'init'"

你的第一期,可以这样写:

    (uuid! as NSUUID).getBytes(mutableData!.mutableBytes.assumingMemoryBound(to: UInt8.self))

但是如果你可以接受 Data 具有相同的原始 UUID 字节,你可以将其写为:

    var uuidBytes = uuid!.uuid
    let data = Data(bytes: &uuidBytes, count: MemoryLayout.size(ofValue: uuidBytes))

你的第二个问题,在Data.init(bytes:count:)中,第一个参数的类型是UnsafeRawPointer,你可以向它传递任意类型的Unsafe(Mutable)Pointer

Using Swift with Cocoa and Objective-C (Swift 3)

检查 Pointers 的常量指针部分。

When a function is declared as taking an UnsafeRawPointer argument, it can accept the same operands as UnsafePointer<Type> for any type Type.

您无需转换指针类型。

    let computedHashData1 = Data(bytes: &hash, count: 20)