On Splitting Function Names in Swift

As Paul Hudson explains, Swift function parameters have external and internal names, the external coming first. Any functions utilising two or more parameters must reference all parameters after the first by their names, the external name if one provided, the internal name if not. So the following functions:

Would be called like this:

The fact that the first parameter does not need to be named is a hangover from Objective-C, which is a euphemistic way of saying: suboptimal. Obviously, Apple would like to attract Objective-C programmers over to Swift, and so they provide such similarities to Objective-C to ease the transition. However, those of us coming to Swift directly - like me - do not approve of these inconsistencies. Clarity is an essential element of "swiftiness," and therefore, if one is passing a parameter to a function, one should be made to state and therefore know what that parameter is:

Both external and internal parameter names are given lowercase names, so that there isn't a weird and ugly inconsistency of function names starting with a lowercase letter, but parameter names starting with an uppercase one.

But, when we start applying this style to certain types of function - the "do-something-by-something" type - this starts to look weird and ugly in a different way:

"Height" is unnecessarily repeated. This is better:

Essentially, part of the function name appears inside the brackets. It may seem counterintuitive, but it's actually an elegant way around the inconsistency brought across from Objective-C. It works well for setters too:

Once you're used to function names like this, you can take this further, and use them everywhere. For instance, here's an actual function in one of my projects:

This does not currently form part of Ray Wenderlich's otherwise excellent Swift Style Guide, but I'm sure only because it hasn't occurred to anyone on their team yet. I hope they include it at a later date.

UPDATE

The release of Swift 3.0 has seen many changes similar to that made to NSDictionary's objectForKey function:

Following my comment about Ray Wenderlich's style guide immediately above - and given that I initially wrote this blog post in February of 2016 - I feel wholly vindicated in my belief that split function names are best practice.

Leave a Reply

Your email address will not be published. Required fields are marked *