Sweeper
Sweeper

Reputation: 271135

Should we add an external parameter name to the first parameter of methods? Why?

Note: I'm only talking about Swift 2 here.

I have seen two kinds of method naming conventions:

func animateWithDuration(duration: NSTimeInterval, animation: () -> Void)

and

func animate(withDuration duration: NSTimeInterval, animation: () -> Void)

I've heard that one of these is more "swifty". But I can't remember which. But why would people even care about this? The two conventions looks almost the same when called:

animateWithDuration(10) { ... }

verses

animate(withDuration: 10) { ... }

When you try to read the method out loud, it's exactly the same words:

animate with duration 10

So which is more swifty and why?

Upvotes: 2

Views: 60

Answers (2)

Rob
Rob

Reputation: 437472

The former syntax is the preferred/default syntax for Swift 2, and the latter is the preferred/default syntax for Swift 3.

In WWDC 2016's video, Swift API Design Guidelines, they describe their impressions of this older, former syntax within the Cocoa APIs:

And so, when you bring all of these APIs that were written for Objective-C into Swift unmodified, they seemed a little bit out of character. They feel a bit not-Swifty.

So, by Apple's own estimation, the new syntax is more Swifty.

Having said that, if you're limiting yourself to considering Swift 2.x, you could easily make an argument for sticking with the traditional syntax for the sake of consistency. Alternatively (and more compellingly, in my opinion), you can start adopting the new syntax where you can do so naturally, to ease the Swift 3 migration path.

But I don't think it's as simple as "always include name of parameter in the method name" or "not". There are cases in Swift 3 where we would define a method whose first parameter would not have an external parameter name (just like in Swift 2 there were cases where we would supply an external name for the first parameter). It's better to let the principles outlined in that video (or as outlined on the swift.org site) govern your method naming practices.

Upvotes: 1

hnh
hnh

Reputation: 14795

It is kinda superfluous to discuss coding styles, there are plenty of arguments for or against one. What somewhat matters is that Swift 3 APIs are going to use the second style, hence it is kinda recommended to use that for Swift code.

Some argument which speaks for the second style is that it is more consistent with multiple arguments, such as

animate(withDuration: 10, andEffect: .Blend)

Another argument is that it makes keyword arguments consistent, e.g. with init:

let a = Animation(withDuration: 10, andEffect: .Blend)

After all the () invocation syntax doesn't play that well with sentence style method invocations in the first place. Smalltalk or ObjC are much better with this (IMO).

Upvotes: 1

Related Questions