Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-01-21

Null, nil and pointers

Note: This article is obsolete for the later versions of Swift.

Optional in Swift have made the use of "non-existing" values easier and safer. However sometimes things can get confusing at the low level APIs that use pointers to pointers.

In most instances we can now use nil were previously null was used.

For example in this API:

func URLForDirectory(_ directoryNSSearchPathDirectory,
            inDomain domainNSSearchPathDomainMask,
   appropriateForURL urlNSURL?,
              create shouldCreateBool,
               error errorNSErrorPointer) -> NSURL?

The appropriateForURL parameter is specified as an optional and can thus safely be specified as a nil.

This call also makes use of the error parameter, which is specified as a NSErrorPointer. This behaves very much like an optional, even though it is not. We can use nil here as well if we do not want to use the error parameter.

At lower level APIs nil is usable as well, for example:

func getaddrinfo(_: UnsafePointer<Int8>,
                 _: UnsafePointer<Int8>,
                 _: UnsafePointer<addrinfo>,
                 _: UnsafeMutablePointer<UnsafeMutablePointer<addrinfo>>) -> Int32

In the first parameter in this function nil can be used, but in the last parameter we may want to use a pointer to a nil, which I have not found possible to construct. But there is a way out, the pointer definitions include a ".null()" function which returns a null-pointer.

In the above example we can pass a pointer to a nul pointer by doing it like this:

    // For the result from the getaddrinfo
    
    var servinfo = UnsafeMutablePointer<addrinfo>.null()
    
    
    // Get the info we need to create our socket descriptor
    
    status = getaddrinfo(
        nil,                        // Any interface
        servicePortNumber,          // The port on which will be listenend
        &hints,                     // Protocol configuration
        &servinfo)                  // The created information

Now the getaddrinfo function has a pointer to a null pointer which it can update to provide the requested information.

As mentioned before, be sure to define the reference servinfo as a 'var' not as a 'let'. Otherwise the '&' won't work.

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