The action selector
will receive the sender
object just like it would if you were using Interface Builder. So your setReminder(_:)
selector could have the signature:
func setReminder(_ sender: Any) {
// Coerce sender to NSMenuItem and use it to make your decisions
}
or:
func setReminder(_ sender: NSMenuItem) {
// Don't do any coercion work you don't need to do…
}
You could also set the tag
property of the NSMenuItem to your delay values. The tag
property is an Int
type so a good match for your values.
As you are creating multiple entries you could use a for in
loop to traverse an array
or dictionary
, creating a new NSMenuItem
for each entry. So we could change your original code to something like this example where I use a dictionary:
let delaySubMenu = NSMenu()
let delays = ["5 Minutes" : 5, "10 Minutes" : 10, "15 Minutes" : 15] // This is a dictionary of String:Int
for (titleKey, value) in delays {
let menuItem = NSMenuItem(title: titleKey, action: #selector(setReminder(_:)), keyEquivalent: nil)
menuItem.tag = value
delaySubMenu.addItem(menuItem)
}
func setReminder(_ sender: NSMenuItem) {
let delayValue = sender.tag // delayValue is a Int by inference from tag
// Do something with your delay value
}
disclaimer: this is just cut and paste in the browser so it may needs some tweaking to actually work.