Wednesday, January 20, 2016 [Tweets] [Favorites]

Swift Named Parameters

Keith Harrison:

The rules for naming parameters in Swift functions and methods have changed for the better over the last few releases but still seem to cause confusion. Here is my quick summary updated for Swift 2.1.

Coming from Objective-C, I still think it feels a bit weird that the declaration and call site don’t match. In Swift declarations, we have external-space-internal-colon-type, whereas at the call site we have external-colon-value. In Objective-C, we have external-colon-(optional type)internal and external-colon-value, which makes sense because the value goes into the internal name. In Objective-C, the external name is always followed by a colon. In Swift, the external name is sometimes followed by a space and sometimes by a colon, and the colon is also used to specify the type. It’s a thorny problem because there is precedent in other languages for both uses of the colon.

3 Comments

At the calls site you also need to remember if the first parameter of the method has an external name, otherwise Xcode raises an error. There are probably better examples out there...

CGRect(x: 0, y: 0, width: 10, height: 10) -> Ok
NSMakeRange(loc: 10, len: 15) -> Extraneous argument labels error

@Neil Isn’t it unusual for the first parameter to have an external name except for initializers?

@Michael, yes I guess that's a good rule of thumb. I couldn't think of any other cases to include an external name for the first parameter.

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment