Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UnsafeMutablePointer in Swift 3?

Tags:

xcode

ios

swift

I have the following code written in Swift 2.2:

let keyData = NSMutableData(length: 64)!
SecRandomCopyBytes(kSecRandomDefault, 64, UnsafeMutablePointer<UInt8>(keyData.mutableBytes))

XCode 8 highlights that second line and claims that

Cannot invoke initializer for type 'UnsafeMutablePointer<_>' with an argument list of type '(UnsafeMutableRawPointer)'

While I appreciate XCode telling me this, I don't quite understand how to change the UnsafeMutableRawPointer to be acceptable.

Does anyone know how to convert this code into Swift 3?

like image 644
AppreciateIt Avatar asked Sep 15 '16 15:09

AppreciateIt


People also ask

What is UnsafeMutablePointer?

UnsafeMutablePointer provides no automated memory management or alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior. Memory that you manually manage can be either untyped or bound to a specific type.

Do we have pointers in Swift?

Swift's typed pointers give you direct access to memory, but only within the confines of type safety. You can't have two typed pointers to the same memory that disagree on the type. So, if your goal is to reinterpret bytes of memory as different types, then you need use a lower-level API.

What is a pointer Swift?

A pointer is a variable that stores the memory address of an object. Swift pointers can be broken down into the following types: A buffer type provides a collection interface to a group of elements stored contiguously in memory so that you can treat them like an array.

What is data in Swift?

Data in Swift 3 is a struct that conforms to collection protocol. It is a collection of bytes ( [UInt8] array of unsigned integer 8 bits 0-255). – Leo Dabus.


1 Answers

I recommend you to work with Data rather than NSData in Swift 3.

var keyData = Data(count: 64)
let result = keyData.withUnsafeMutableBytes {mutableBytes in
    SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
}

withUnsafeMutableBytes(_:) is declared as a generic method, so, in simple cases such as this, you can use it without specifying element type.

like image 136
OOPer Avatar answered Nov 15 '22 18:11

OOPer