UnsafePointer<UInt8> initializer in Swift 3

 ̄綄美尐妖づ 提交于 2019-12-20 17:50:15

问题


I have a receipt validation class that is deprecated since Swift 3 has released. I fixed some issues, but I still have many ...

Here is the GitHub source code I used : https://gist.github.com/baileysh9/4386ea92b047d97c7285#file-parsing_productids-swift and https://gist.github.com/baileysh9/eddcba49d544635b3cf5

  1. First Error :

        var p = UnsafePointer<UInt8>(data.bytes)
    

Compiler throws : Cannot invoke initializer for type UnsafePointer(UInt8) with an argument list of type UnsafeRawPointer

  1. Second error

    while (ptr < end)
    

Binary operators < cannot be applied to two UnsafePointer(UInt8) operands

Thank you very much in advance :)

EDIT

Thanks to LinShiwei answer I found a solution to UnsafePointer declaration. It compiles but not tested yet (because other errors avoid me to test) :

 func getProductIdFromReceipt(_ data:Data) -> String?
{
  let tempData: NSMutableData = NSMutableData(length: 26)!
  data.withUnsafeBytes {
        tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: $0)
    }

    var p: UnsafePointer? = tempData.bytes.assumingMemoryBound(to: UInt8.self)

回答1:


  1. In Swift 3, you cannot init an UnsafePointer using an UnsafeRawPointer.

    You can use assumingMemoryBound(to:) to convert an UnsafeRawPointer into an UnsafePointer<T>. Like this:

    var ptr = data.bytes.assumingMemoryBound(to: UInt8.self)
    
  2. Use debugDescription or distance(to:) to compare two pointer.

    while(ptr.debugDescription < endPtr.debugDescription)
    

    or

    while(ptr.distance(to:endPtr) > 0)
    



回答2:


May have recently changed to just this, without the ".bytes." part:

var p: UnsafePointer = data.assumingMemoryBound(to: UInt8.self)

from the original:

var p = UnsafePointer<UInt8>(data.bytes)


来源:https://stackoverflow.com/questions/39747190/unsafepointeruint8-initializer-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!