Friday, April 03, 2015

With Autocompleted Methods & Functions, I Wish Returned Values Came After the Call In Swift

We’ve been calling functions or methods on objects the same since at least C appeared in 1972. You declare & call a function like this:

int main(void) {
    printf("hello, world\n");
    return 0;
}
int value = main();

To define, the return type is declared before the name of the function. On call, a variable is declared to hold the return value of the function call.

In Swift, you declare a function with a return type like this:

  • func printAndCount(stringToPrint: String) -> Int {

        println(stringToPrint)

        return countElements(stringToPrint)

    }

I loved this change to the C convention. IMHO, the information importance follows the order you declare the function: name, parameter type(s), and return type(s). However, you still call that function like this:

  • let count = printAndCount("Hello, playground")

This feels like a job half done, a little bit like the tail wagging the dog

I nearly always know the name of a function or method I want to call before I know its return types.

Wouldn’t it be great if the language was fully adapted to the pervasiveness of autocomplete?

Imagine the amount of time you’d save if you could start typing the name of the function or method first and let autocomplete show & then fill in the return types?

Proposing Post Call Return Value Assignment

I’m proposing that variables that are assigned the return value of a function should come after the function call using a return arrow. It would look something like this:

printAndCount("Hello, playground") -> let count

With methods, it would look like this:

someObject.printAndCount("Hello, playground") -> let count

The actual syntax is up for debate, but I’m excited by the idea. I don’t know of another language that does this.

Pros

  • Far fewer trips to documentation to lookup the return types of a function you know the beginning of.
  • Far less typing of return types of any kind
  • Far less (no?) typing the object, autocompleting the method, then fixing up the return types to variables you want.

Cons

  • Return variables harder to “find” when reading code
    • Listing for completeness, I don’t see it being materially wrong, just different from the norm
  • Imagine the style debates because the existing way stays in the language.

I’m betting the pros would outweigh any cons, and this feature would greatly increase the usability of the language and editor together.