The "&" is used in arguments to create a pointer. But cannot be used in other places for the same purpose.
So how to create a pointer outside of a function argument?
Well, Apple has provided us with the withUnsafeMutablePointer and withUnsafePointer functions to deal with this. They take a few arguments and a closure. The argument is converted into a pointer that can subsequently be used inside the closure.
An example:
var telemetry = Telemetry()
let result = withUnsafeMutablePointer(&telemetry, {
ptr in
// From here on 'ptr' is a UnsafeMutablePointer<Telemetry>
...
})
And there are variations on withUnsafeMutablePointer and withUnsafePointer that allow for multiple pointers to be created at once.
The result is the result returned from the closure, which is neat too. In fact the conversion functions are defined as this:
public func withUnsafeMutablePointer<T, Result>(inout arg: T, @noescape _ body: UnsafeMutablePointer<T> throws -> Result) rethrows -> Result
Happy coding...
Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH
We don't get the world we wish for... we get the world we pay for.
No comments:
Post a Comment