Allow use of named-argument syntax for positional arguments?

The trouble with this is that you need to know which arguments passed with key = val syntax are positional and which are keyword arguments before you can choose a method. But you don’t know that until you’ve selected a method. For example, if I see f(x = 1, y = 2, z = 3) how do I know which subset of x, y and z are positional and should be used to dispatch f and which are keywords and should be ignored during dispatch? There are 8 = 2^3 possibilities to consider and that number grows exponentially with the number of arguments.

As a higher level observation, Swift was designed to appeal to and make sense to a large existing base of Objective-C programmers and Objective-C does some very unusual stuff with keyword names and dispatch. When someone writes [obj name:argument] in Objective-C, the name is the name of the method that’s sent to obj. So the “keyword names” are actually the name of the method to invoke—any dispatch that’s done happens after looking at the set of keyword names. That’s kind of the opposite of what Julia does, where the dispatch is done ignoring keyword arguments and then keyword values are used to pass additional data to the selected method as though they’d just been assigned at the top of the method body.

More generally when it comes to APIs, if the arguments to a function need labels in order for the call’s meaning to be clear, then the API should probably be reconsidered. Either the arguments should be keywords so that the name is required, or as has been suggested, you could use a structure to hold the options.

4 Likes