Monday, June 15, 2026
HomeiOS DevelopmentThe right way to construct macOS apps utilizing solely the Swift Bundle...

The right way to construct macOS apps utilizing solely the Swift Bundle Supervisor?

[ad_1]

Swift scripts and macOS apps

Swift compiler 101, you possibly can create, construct and run a Swift file utilizing the swiftc command. Contemplate the most straightforward Swift program that we will all think about in a fundamental.swift file:

print("Hiya world!")

In Swift if we wish to print one thing, we do not even must import the Basis framework, we will merely compile and run this piece of code by operating the next:

swiftc fundamental.swift 	# compile fundamental.swift
chmod +x fundamental 		# add the executable permission
./fundamental 			# run the binary

The excellent news that we will take this one step additional by auto-invoking the Swift compiler below the hood with a shebang.

#! /usr/bin/swift

print("Hiya world!")

Now in case you merely run the ./fundamental.swift file it’s going to print out the well-known “Hiya world!” textual content. 👋

Because of the program-loader mechanism and naturally the Swift interpreter we will skip an additional step and run our single-source Swift code as simple as an everyday shell script. The excellent news is that we will import all type of system frameworks which are a part of the Swift toolchain. With the assistance of Basis we will construct fairly helpful or utterly ineffective command line utilities.

#!/usr/bin/env swift

import Basis
import Dispatch

guard CommandLine.arguments.depend == 2 else {
    fatalError("Invalid arguments")
}
let urlString =  CommandLine.arguments[1]
guard let url = URL(string: urlString) else {
    fatalError("Invalid URL")   
}

struct Todo: Codable {
    let title: String
    let accomplished: Bool
}

let activity = URLSession.shared.dataTask(with: url) { knowledge, response, error in 
    if let error = error {
        fatalError("Error: (error.localizedDescription)")
    }
    guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
        fatalError("Error: invalid HTTP response code")
    }
    guard let knowledge = knowledge else {
        fatalError("Error: lacking response knowledge")
    }

    do {
        let decoder = JSONDecoder()
        let todos = strive decoder.decode([Todo].self, from: knowledge)
        print("Listing of todos:")
        print(todos.map { " - [" + ($0.completed ? "✅" : "❌") + "] ($0.title)" }.joined(separator: "n"))
        exit(0)
    }
    catch {
        fatalError("Error: (error.localizedDescription)")
    }
}
activity.resume()
dispatchMain()

In case you name this instance with a URL that may return an inventory of todos it’s going to print a pleasant record of the gadgets.

./fundamental.swift https://jsonplaceholder.typicode.com/todos

Sure, you possibly can say that this script is totally ineffective, however for my part it is a tremendous demo app, because it covers learn how to examine command line arguments (CommandLine.arguments), it additionally reveals you learn how to wait (dispatchMain) for an async activity, reminiscent of a HTTP name by way of the community utilizing the URLSession API to complete and exit utilizing the suitable technique when one thing fails (fatalError) or in case you attain the tip of execution (exit(0)). Just some strains of code, however it comprises a lot data.

Have you ever seen the brand new shebang? In case you have a number of Swift variations put in in your system, you should use the env shebang to go together with the primary one which’s out there in your PATH.

It is not simply Basis, however you possibly can import AppKit and even SwiftUI. Nicely, not below Linux after all, since these frameworks are solely out there for macOS plus you have to Xcode put in in your system, since some stuff in Swift the toolchain continues to be tied to the IDE, however why? 😢

Anyway, again to the subject, this is the boilerplate code for a macOS utility Swift script that may be began from the Terminal with one easy ./fundamental.swift command and nothing extra.

#!/usr/bin/env swift

import AppKit
import SwiftUI

@out there(macOS 10.15, *)
struct HelloView: View {
    var physique: some View {
        Textual content("Hiya world!")
    }
}

@out there(macOS 10.15, *)
class WindowDelegate: NSObject, NSWindowDelegate {

    func windowWillClose(_ notification: Notification) {
        NSApplication.shared.terminate(0)
    }
}


@out there(macOS 10.15, *)
class AppDelegate: NSObject, NSApplicationDelegate {
    let window = NSWindow()
    let windowDelegate = WindowDelegate()

    func applicationDidFinishLaunching(_ notification: Notification) {
        let appMenu = NSMenuItem()
        appMenu.submenu = NSMenu()
        appMenu.submenu?.addItem(NSMenuItem(title: "Stop", motion: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
        let mainMenu = NSMenu(title: "My Swift Script")
        mainMenu.addItem(appMenu)
        NSApplication.shared.mainMenu = mainMenu
        
        let measurement = CGSize(width: 480, top: 270)
        window.setContentSize(measurement)
        window.styleMask = [.closable, .miniaturizable, .resizable, .titled]
        window.delegate = windowDelegate
        window.title = "My Swift Script"

        let view = NSHostingView(rootView: HelloView())
        view.body = CGRect(origin: .zero, measurement: measurement)
        view.autoresizingMask = [.height, .width]
        window.contentView!.addSubview(view)
        window.middle()
        window.makeKeyAndOrderFront(window)
        
        NSApp.setActivationPolicy(.common)
        NSApp.activate(ignoringOtherApps: true)
    }
}

let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.run()

Particular thanks goes to karwa for the authentic gist. Additionally in case you are into Storyboard-less macOS app improvement, it is best to undoubtedly check out this text by @kicsipixel. These assets helped me quite a bit to place collectively what I wanted. I nonetheless needed to prolong the gist with a correct menu setup and the activation coverage, however now this model acts like a real-world macOS utility that works like a appeal. There is just one challenge right here… the script file is getting crowded. 🙈

Swift Bundle Supervisor and macOS apps

So, if we comply with the identical logic, which means we will construct an executable package deal that may invoke AppKit associated stuff utilizing the Swift Bundle Supervisor. Simple as a pie. 🥧

mkdir MyApp
cd MyApp 
swift package deal init --type=executable

Now we will separate the elements into standalone recordsdata, we will additionally take away the supply checking, since we will add a platform constraint utilizing our Bundle.swift manifest file. If you do not know a lot about how the Swift Bundle Supervisor works, please learn my SPM tutorial, or in case you are merely curious concerning the construction of a Bundle.swift file, you possibly can learn my article concerning the Swift Bundle manifest file. Let’s begin with the manifest updates.


import PackageDescription

let package deal = Bundle(
    title: "MyApp",
    platforms: [
        .macOS(.v10_15)
    ],
    dependencies: [
        
    ],
    targets: [
        .target(name: "MyApp", dependencies: []),
        .testTarget(title: "MyAppTests", dependencies: ["MyApp"]),
    ]
)

Now we will place the HelloView struct into a brand new HelloView.swift file.

import SwiftUI

struct HelloView: View {
    var physique: some View {
        Textual content("Hiya world!")
    }
}

The window delegate can have its personal place inside a WindowDelegate.swift file.

import AppKit

class WindowDelegate: NSObject, NSWindowDelegate {

    func windowWillClose(_ notification: Notification) {
        NSApplication.shared.terminate(0)
    }
}

We are able to apply the identical factor to the AppDelegate class.

import AppKit
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    let window = NSWindow()
    let windowDelegate = WindowDelegate()

    func applicationDidFinishLaunching(_ notification: Notification) {
        let appMenu = NSMenuItem()
        appMenu.submenu = NSMenu()
        appMenu.submenu?.addItem(NSMenuItem(title: "Stop", motion: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
        let mainMenu = NSMenu(title: "My Swift Script")
        mainMenu.addItem(appMenu)
        NSApplication.shared.mainMenu = mainMenu
        
        let measurement = CGSize(width: 480, top: 270)
        window.setContentSize(measurement)
        window.styleMask = [.closable, .miniaturizable, .resizable, .titled]
        window.delegate = windowDelegate
        window.title = "My Swift Script"

        let view = NSHostingView(rootView: HelloView())
        view.body = CGRect(origin: .zero, measurement: measurement)
        view.autoresizingMask = [.height, .width]
        window.contentView!.addSubview(view)
        window.middle()
        window.makeKeyAndOrderFront(window)
        
        NSApp.setActivationPolicy(.common)
        NSApp.activate(ignoringOtherApps: true)
    }
}

Lastly we will replace the primary.swift file and provoke every part that must be executed.

import AppKit

let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.run()

The excellent news is that this method works, so you possibly can develop, construct and run apps regionally, however sadly you possibly can’t submit them to the Mac App Retailer, because the ultimate utility package deal will not appear to be an actual macOS bundle. The binary will not be code signed, plus you may want an actual macOS goal in Xcode to submit the applying. Then why trouble with this method?

Nicely, simply because it’s enjoyable and I may even keep away from utilizing Xcode with the assistance of SourceKit-LSP and a few Editor configuration. The perfect half is that SourceKit-LSP is now a part of Xcode, so you do not have to put in something particular, simply configure your favourite IDE and begin coding.

You may also bundle assets, since this function is accessible from Swift 5.3, and use them by way of the Bundle.module variable if wanted. I already tried this, works fairly effectively, and it’s so a lot enjoyable to develop apps for the mac with out the additional overhead that Xcode comes with. 🥳



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments