Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UnsafeMutablePointer in swift 4

Objective-c has a concept of a pointer to a pointer. If you dereference the first pointer you can access the original

void makeFive(int *n) {
    *n = 5;
}

int n = 0;
makeFive(&n);
// n is now 5

When this is bridged to Swift 3 it becomes an UnsafeMutablePointer

func makeFive(_ n: UnsafeMutablePointer<Int>) {
    n.memory = 5
}
var n: Int = 0
makeFive(&n)
// n is now 5

However, as of Swift 4, this behavior has changed and the memory property is no longer available.

What would be the swift 4 equivalent of the makeFive(_:) function?

Update Thanks to Hamish, I now know that "memory" was renamed to pointee.

like image 386
DerrickHo328 Avatar asked Sep 20 '17 18:09

DerrickHo328


People also ask

What is UnsafeMutablePointer in Swift?

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.

What is Opaquepointer in Swift?

Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.

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 mutable pointer?

The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, the this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members.


1 Answers

Please check : https://developer.apple.com/documentation/swift/unsafemutablepointer

func makeFive(_ n: UnsafeMutablePointer<Int>) {
    n.initialize(to: 5)
}
var n: Int = 0
makeFive(&n)
// n is now 5
like image 150
Vini App Avatar answered Sep 19 '22 20:09

Vini App