quitting xcode cocoa swift app

27,012

Solution 1

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)
}

Solution 2

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.

Solution 3

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

Share:
27,012
Lanny Rosicky
Author by

Lanny Rosicky

Still coding, after all these years - on the way from Assembler 360 to OOP Swift

Updated on July 09, 2022

Comments

  • Lanny Rosicky
    Lanny Rosicky almost 2 years

    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.

  • Lanny Rosicky
    Lanny Rosicky almost 10 years
    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.
  • Mike S
    Mike S almost 10 years
    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.
  • Amr Angry
    Amr Angry over 7 years
    error in syntax --> for swift 3 solution ---> use if unravel identifier
  • SaganRitual
    SaganRitual over 6 years
    As of Swift 4, it's NSApplication.shared.terminate(self)
  • Zeeshan Suleman
    Zeeshan Suleman about 3 years
    If you terminate using this, then the app would not open again if you want to open it programmatically