3

This is something I see all over Cocoa:

func someAction(_ sender: Any)

which is called like:

someAction(someObject)

This can be very confusing to me. The infamous example is in NSView subclasses:

print("Hello, World!")

Despite this being standard Swift syntax for printing to the console, in an NSView, this will open the printer dialog, claiming the sender is the String "Hello, World!". So, in my code I started doing this:

func someAction(sender: Any)

but I fear that the fact I see none of this in Cocoa means it's an anti-pattern. Is that the case, or am I in the right?

1 Answer 1

4

No, it isn't. Pure Swift probably doesn't use the _, and rather prefers sender, or a label and then a variable name. The use of the _ all over Swift code translated from Cocoa is because that's just how the Obj-C gets translated to Swift 3 thanks to this change. Swift 3 rationale behind naming.

Perhaps, if you are working closely with Obj-C and/or Cocoa and want to keep your naming conventions the same, you could use the _, but it is certainly not required. Here is an example straight from Apple's docs of acceptable Swift 3 code that does not use the _:

import UIKit

class MyViewController: UIViewController {
    let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))

    override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        let action = #selector(MyViewController.tappedButton)
        myButton.addTarget(self, action: action, forControlEvents: .touchUpInside)
    }

    func tappedButton(sender: UIButton?) {
        print("tapped button")
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.