Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
When should you omit a parameter label? - a free tutorial

NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

When should you omit a parameter label?

Paul Hudson    @twostraws   

If we use an underscore for a function parameter’s external label, Swift lets us use no name for that parameter at all. This is very common practice in some parts of Swiftly development, particularly when building apps that don’t use SwiftUI, but there are many other times when you’ll also want to use this.

The main reason for skipping a parameter name is when your function name is a verb and the first parameter is a noun the verb is acting on. For example:

  • Greeting a person would be greet(taylor) rather than greet(person: taylor)
  • Buying a product would be buy(toothbrush) rather than buy(item: toothbrush)
  • Finding a customer would be find(customer) rather than find(user: customer)

This is particularly important when the parameter label is likely to be the same as the name of whatever you’re passing in:

  • Singing a song would be sing(song) rather than sing(song: song)
  • Enabling an alarm would be enable(alarm) rather than enable(alarm: alarm)
  • Reading a book would be read(book) rather than read(book: book)

Before SwiftUI came along, apps were build using Apple’s UIKit, AppKit, and WatchKit frameworks, which were designed using an older language called Objective-C. In that language, the first parameter to a function was always left unnamed, and so when you use those frameworks in Swift you’ll see lots of functions that have underscores for their first parameter label to preserve interoperability with Objective-C.

Hacking with Swift is sponsored by ViRE

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Download on the App Store

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.