Hacker News new | past | comments | ask | show | jobs | submit login

Having never used Swift, it feels like the syntax is being optimized for the less-common case; are named parameters considered the "default" choice in Swift, and is using different external names so common that it's worth cluttering the syntax for functions without external parameters in order to make the their own syntax easier?



Named parameters are very much the default in Swift. Positional parameters are rare exceptions.

The internal/external name divide often works out beautifully. For example, let's equip Double with a multiply-add. An idiomatic Swift signature:

    extension Double {
      func multiply(by multiplier:Double, adding summand:Double) -> Double {
        return self * multiplier + summand
      }
    }

    print(3.multiply(by:4, adding:5))
Erase punctuation and you have:

    func multiply by multiplier adding summand

    print 3 multiply by 4 adding 5
The caller sees an action (multiply by, adding), the callee sees nouns (multiplier, summand). It's fantastically readable.


The javascript equivalent would be something like

    Number.prototype.multiply = function({by:multiplier, adding:summand = 0}) {
	return this * multiplier + summand
    }

    console.log((3).multiply({by: 4, adding: 5}))
But of course, javascript APIs are hardly ever written like that. I think it's interesting how the norms of your ecosystem and very small differences in ergonomics in expression make a big difference in behaviour.


You can argue if it's useful or not on its own, but it makes sense when you consider that Swift is compatible with Objective-C. In Objective-C, that function would be a method like

    -(void) greetWith:(NSString *)greeting to:(NSString *)personName
and you'd call it like

    [self greetWith:@"Hello" to:@"Bob"]
Swift's external/internal parameters are built to allow the same style as was used with Objective-C and easy bridging. Swift's APIs tend to be terser than Objective-C ones, though.


> are named parameters considered the "default" choice in Swift

Most definitely yes. In fact it used to be that the first parameter was implicitly positional (in Swift 2 IIRC), this was removed to make all parameters named by default.

And do note that you can provide a single label for a parameter, it will be used as both "internal" and "external" names:

    func foo(bar: String) {
        print(bar);
    }
    foo(bar: "3")

    func baz(qux quux: String) {
        print(quux);
    }
    baz(qux: "4")
> and is using different external names so common

Also yes, it's absolutely ubiquitous, if only because that's the one way to provide "positional" parameter.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: