Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usecase for ignored parameters in Swift

In Swift, you can write the following:

func foo(_:Int) -> { return 1 }

Where the underscore is an ignored parameter. I only know this because of the documentation, but cannot think of ANY usecase on why you would even do this. Am I missing something?

like image 611
Justin Pihony Avatar asked Jun 21 '14 03:06

Justin Pihony


2 Answers

Ignoring parameters (or members of a tuple, which are pretty close to the same thing) makes sense when:

  • You're overriding a superclass function or implementing a function defined by a protocol, but your implementation of that function doesn't need one of the parameters. For example, if you hook app launching but don't need a reference to the shared UIApplication instance in that method:

    override func application(_: UIApplication!, didFinishLaunchingWithOptions _: NSDictionary!) -> Bool { /* ... */ }
    
  • You're providing a closure (aka block in ObjC) as a parameter to some API, but your use of that API doesn't care about one of the parameters to the closure. For example, if you're submitting changes to the Photos library and want to throw caution to the wind, you can ignore the success and error parameters in the completion handler:

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
        // change requests
    }, completionHandler: { _, _ in
        NSLog("Changes complete. Did they succeed? Who knows!")
    })
    
  • You're calling a function/method that provides multiple return values, but don't care about one of them. For example, assuming a hypothetical NSColor method that returned components as a tuple, you could ignore alpha:

    let (r, g, b, _) = color.getComponents()
    

The reasoning behind this is that it makes your code more readable. If you declare a local name for a parameter (or tuple member) that you don't end up using, someone else reading your code (who could well be just the several-months-later version of yourself) might see that name and wonder where or how it gets used in the function body. If you declare upfront that you're ignoring that parameter (or tuple member), it makes it clear that there's no need to worry about it in that scope. (In theory, this could also provide an optimization hint to the complier, which might make your code run faster, too.)

like image 186
rickster Avatar answered Oct 20 '22 14:10

rickster


Perhaps you're overriding a method and your override ignores one of the parameters? Making it clear that you're ignoring the parameter saves future coders from having to look through your code to work out that it's not using the parameter and makes it clear that this was intentional. Or maybe it's to create some sort of Adapter pattern where you make it clear that one of the parameters is being ignored.

like image 28
ikuramedia Avatar answered Oct 20 '22 15:10

ikuramedia