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

2015-11-19

Namespaces in Swift, resolving collisions.

Though Swift does support namespaces, it is not obvious what the namespace is for the standard libraries. This can easily create conflicts when we want to name a function of our own making and happen to pick the same name as a standard function. And there are a lot of standard functions...

Often enough the argument list of a function will prove to be sufficient for the compile to figure out which function we did intent to call, but there are cases where the compiler needs some assistance.

For example the UNIX accept function is defined as follows:

int accept(int, struct sockaddr * __restrict, socklen_t * __restrict)

I defined an accept function with the following signature:

class SocketUtils {
        
    static func accept(socket: Int32, interval: NSTimeInterval?, timeout: NSTimeInterval? = nil) -> AcceptResult { .. }
}

Unfortunately the compiler will nag when I try to use the Unix accept function:


Obviously the compiler thinks that my own accept function should be used, while I want to use the accept from the UNIX system library.

The solution is simple: use the fully qualified name for the system function.

Turns out, the fully qualified name for any system function starts with the name of the project:

let connectionDescriptor = MyGreatProject.accept(socket, &connectedAddrInfo, &connectedAddrInfoLength)

Works just fine!

Note: The fully qualified name for my own accept function is of course:
MyGreatProject.SocketUtils.accept

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