Sitemap
CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Follow publication

Member-only story

macOS: Terminating the App the SwiftUI way

3 min readMay 24, 2024

--

Photo by Super Snapper on Unsplash

SwiftUI extensively makes use of the environment to pass down functionality. For example: dismiss (an action that dismisses the current presentation) and openURL (an action that opens a URL).

As of writing (2024, before WWDC) there is no SwiftUI way to terminate the app in a macOS app so let’s fix that.

The command to terminate the application is:
NSApplication.shared.terminate(nil)

This one line of code is simple enough to include in your app, but this story is about the SwiftUI approach. Hopefully it will give you more insight on how an Action, as they are called in SwiftUI, are produced in the hope you are able to learn from it and apply it to other parts of your app that may benefit from this approach.

TerminateApplicationAction

Just like almost everything in Swift, we start of with a struct.

struct TerminateApplicationAction {
let action: () -> ()
func callAsFunction() { action() }
}

Note the inclusion of a special function named callAsFunction. This is a new Swift 5.2 feature that allows us to call instances of types as functions. Or, as the Swift Evolution Proposal calls it “Callable values of user-defined nominal types”.

--

--

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Mark van Wijnen
Mark van Wijnen

Written by Mark van Wijnen

macOS/iPadOS/iOS/watchOS/visionOS developer and SwiftUI enthousiast. “Stay Hungry, Stay Foolish!” — Steve Jobs

No responses yet