UnsafePointer<UInt8> initializer in Swift 3
In Swift 3, you cannot init an
UnsafePointer
using anUnsafeRawPointer
.You can use
assumingMemoryBound(to:)
to convert anUnsafeRawPointer
into anUnsafePointer<T>
. Like this:var ptr = data.bytes.assumingMemoryBound(to: UInt8.self)
Use
debugDescription
ordistance(to:)
to compare two pointer.while(ptr.debugDescription < endPtr.debugDescription)
or
while(ptr.distance(to:endPtr) > 0)
Related videos on Youtube
GrayFox
Updated on June 09, 2020Comments
-
GrayFox about 4 years
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
-
First Error :
var p = UnsafePointer<UInt8>(data.bytes)
Compiler throws : Cannot invoke initializer for type UnsafePointer(UInt8) with an argument list of type UnsafeRawPointer
-
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)
-
-
GrayFox over 7 yearsOkay thank you, this helped :) ! I Edit my question to add my new code because it is a bit more complex
-
LinShiwei over 7 years@GrayFox What's the problem?
-
GrayFox over 7 yearsdata.bytes.assumingMemoryBound(to: UInt8.self) doesn't work because 'bytes' throws a compiler error : "needs to use UnsafeBytes instead of bytes". I added the entire block into EDIT section ;). Now, this works but I have other new errors in device.identifierForVendor.getBytes(UnsafeMutablePointer(mutableData!.mutableBytes)) which is : "Cannot invoke init of type UnsafeMutablePointer with argument list of type UnsafeMutableRawPointer" ....
-
LinShiwei over 7 yearsUsing
assumingMemoryBound(to:)
again to convertUnsafeMutableRawPointer
intoUnsafeMutablePointer
:)