If we use an underscore for a function parameter’s external label, Swift lets 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:
greet(taylor)
rather than greet(person: taylor)
buy(toothbrush)
rather than buy(item: toothbrush)
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:
sing(song)
rather than sing(song: song)
enable(alarm)
rather than enable(alarm: alarm)
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.
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.