Swift 2.1 action code not working on latest Swift / Version 8.0 (8A218a)

I'm trying to add a clickable button to status bar. If I compile I get no errors but button action does not work. I think it's because of the legacy code but I can't find the issue.

The code in AppDelegate.swift

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength);
let menu = NSMenu();

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    if let button = statusItem.button {
        button.image = NSImage(named: "globe")
        button.action = Selector("showWeather")
    }
}

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
}

func showWeather(sender: NSStatusBarButton) {
    print("Shunshine");
}

}

I get a warning, but If I apply, code does not work neither. I'm compiling a cocoa app for macOS 10.2.

Thanks!!

I found the solution!!!

Replace button.action = Selector("showWeather")

for button.action = #selector(showWeather(sender:))

and that's it!

1 Like

Again, this is really a forums.developer.apple.com question, but the reason it didn't work is more about Swift.

The @objc selector corresponding to your showWeather function is actually "showWeatherWithSender:". That's because there's been a change since Swift 2.1 where the first argument's external label now defaults to sender, not _. So you really should have declared the function like this:

func showWeather(_ sender: NSStatusBarButton)

or, better still:

@IBAction func showWeather(_ sender: NSStatusBarButton)

However, there's a second problem. Colons matter in selectors. Even with the above revised declaration, the selector string should be "showWeather:", not "showWeather".

Of course, using #selector takes care of all these details for you, so you got to the right answer in the end.

1 Like

Thanks Quincey for your help. I'm learning right now. I have zero background on Swift programing language and sometimes lose a lot of time in specific Swift related details. Not to mention Swift changes from version to version and some tutorials get outdated with frequency.

I'll check forums.developer.apple.com anyway :slight_smile:

Thank you very much!