41

I have written my first swift OS/X application in XCode 6. It all works except I cannot figure out how to exit the app. I have a button to exit and the ExitNow function defined as follows:

@IBAction func ExitNow(sender: AnyObject) {
    // ???
}

I cannot figure out what the code would be. By searching online I've found various options, but they were either in Objective C or too general for me to comprehend. I would appreciate an example which would behave the same way as cmd-Q.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lanny Rosicky
  • 603
  • 1
  • 6
  • 9

3 Answers3

91

You should be able to just call terminate on the global NSApp object.


Swift 4 & 5:

@IBAction func ExitNow(sender: AnyObject) {
    NSApplication.shared.terminate(self)
}

Swift 3:

@IBAction func ExitNow(sender: AnyObject) {
    NSApplication.shared().terminate(self)
}

Swift 2:

@IBAction func ExitNow(sender: AnyObject) {
    NSApplication.sharedApplication().terminate(self)
}
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
Mike S
  • 41,895
  • 11
  • 89
  • 84
  • 1
    This I tried and got the following error NSApp.terminate(self)'terminate' is unavailale. APIs deprecated as of OS X 10.9 and earlier are unavailable in Swift. – Lanny Rosicky Aug 13 '14 at 10:03
  • 2
    Oops, apparently you can't use that with NSApp, sorry. I edited my answer so that it uses `NSApplication.sharedApplication()` instead. I also tested it real quick in a brand new OSX Swift project targeting 10.10 and it worked fine. – Mike S Aug 13 '14 at 15:24
  • error in syntax --> for swift 3 solution ---> use if unravel identifier – Amr Angry Feb 14 '17 at 14:44
  • 7
    As of Swift 4, it's `NSApplication.shared.terminate(self)` – SaganRitual Jan 28 '18 at 10:21
  • If you terminate using this, then the app would not open again if you want to open it programmatically – Zeeshan Suleman Mar 26 '21 at 10:09
17

Or we could simply exit from the app like this:

@IBAction func ExitNow(sender: AnyObject) {    
    exit(0)
}

As a side note you can exit because of an error:

fatalError("reason for exiting")

Unconditionally prints a message and stops execution. iOS 8.1 and later.

oyalhi
  • 3,834
  • 4
  • 40
  • 45
4

In Xcode 9.0 you might use NSApp.terminate(nil).

Peter Ahlberg
  • 1,359
  • 2
  • 24
  • 26