Slide 1

Slide 1 text

Delightful Swift CLI Applications

Slide 2

Slide 2 text

Senior software engineer based in Manchester Hi! I’m Pol

Slide 3

Slide 3 text

Content creation Apps I am working on Public speaking

Slide 4

Slide 4 text

Content creation Apps I am working on Public speaking

Slide 5

Slide 5 text

Content creation Apps I am working on Public speaking

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Ask your questions! slido.com #SL23

Slide 9

Slide 9 text

Advanced Swift CLIs Apple frameworks Bundle identifiers Styling libraries Parse arguments Read user input Show SwiftUI views

Slide 10

Slide 10 text

MusiCLI

Slide 11

Slide 11 text

Why though? Low memory footprint Mature ecosystem Cross-platform Statically typed Safely concurrent Familiar

Slide 12

Slide 12 text

Familiar

Slide 13

Slide 13 text

Creating an executable

Slide 14

Slide 14 text

swift package init -- type executable

Slide 15

Slide 15 text

// swift-tools-version: 5.9 import PackageDescription let package = Package( name: "MusiCLI", dependencies: [], targets: [ .executableTarget( name: "MusiCLI", dependencies: [ ] ) ] )

Slide 16

Slide 16 text

// The Swift Programming Language // https: // docs.swift.org/swift-book print("Hello, world!")

Slide 17

Slide 17 text

swift run

Slide 18

Slide 18 text

The first command

Slide 19

Slide 19 text

Best. Library. Ever! https://github.com/apple/swift-argument-parser

Slide 20

Slide 20 text

// swift-tools-version: 5.9 import PackageDescription let package = Package( name: "Musicli", platforms: [.macOS(.v12)], dependencies: [ ], targets: [ .executableTarget( name: "Musicli", dependencies: [] ), ] )

Slide 21

Slide 21 text

// swift-tools-version: 5.9 import PackageDescription let package = Package( name: "Musicli", platforms: [.macOS(.v12)], dependencies: [ .package(url: "https: // github.com/apple/swift-argument-parser.git", exact: "1.2.3") ], targets: [ .executableTarget( name: "Musicli", dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")] ), ] )

Slide 22

Slide 22 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { } }

Slide 23

Slide 23 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { } }

Slide 24

Slide 24 text

The file can’t be called main!

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { } }

Slide 27

Slide 27 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { } }

Slide 28

Slide 28 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } } private func isAppAuthorised() async - > Bool { guard MusicAuthorization.currentStatus != .authorized else { return true } let response = await MusicAuthorization.request() return response == .authorized } }

Slide 29

Slide 29 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } } private func isAppAuthorised() async - > Bool { guard MusicAuthorization.currentStatus != .authorized else { return true } let response = await MusicAuthorization.request() return response == .authorized } }

Slide 30

Slide 30 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() } private func isAppAuthorised() async - > Bool { guard MusicAuthorization.currentStatus != .authorized else { return true } let response = await MusicAuthorization.request() return response == .authorized } }

Slide 31

Slide 31 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: " + song.title) print("Artist: " + song.artistName) print("Album: " + song.albumTitle!) print("Genres: " + song.genreNames.joined(separator: ", ")) print("") } } private func isAppAuthorised() async - > Bool { guard MusicAuthorization.currentStatus != .authorized else { return true } let response = await MusicAuthorization.request() return response == .authorized } }

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

I went down a rabbit hole

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

// swift-tools-version: 5.9 import PackageDescription let package = Package( name: "Musicli", platforms: [.macOS(.v12)], products: [ .executable(name: "Musicli", targets: ["Musicli"]) ], dependencies: [ .package(url: "https: // github.com/apple/swift-argument-parser.git", exact: "1.2.3") ], targets: [ .executableTarget( name: "Musicli", dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")], linkerSettings: [ .unsafeFlags([ "-Xlinker", "-sectcreate", "-Xlinker", " __ TEXT", "-Xlinker", " __ info_plist", "-Xlinker", "Sources/Resources/Info.plist" ]) ] ), ] ) https://forums.swift.org/t/swift-package-manager-use-of-info-plist-use-for-apps/6532/13

Slide 41

Slide 41 text

// swift-tools-version: 5.9 import PackageDescription let package = Package( name: "Musicli", platforms: [.macOS(.v12)], products: [ .executable(name: "Musicli", targets: ["Musicli"]) ], dependencies: [ .package(url: "https: // github.com/apple/swift-argument-parser.git", exact: "1.2.3") ], targets: [ .executableTarget( name: "Musicli", dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")], linkerSettings: [ .unsafeFlags([ "-Xlinker", "-sectcreate", "-Xlinker", " __ TEXT", "-Xlinker", " __ info_plist", "-Xlinker", "Sources/Resources/Info.plist" ]) ] ), ] ) https://forums.swift.org/t/swift-package-manager-use-of-info-plist-use-for-apps/6532/13

Slide 42

Slide 42 text

Apple DOES use this pattern

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

Find out more about it… https://developer.apple.com/library/archive/documentation/Security/Conceptual/CodeSigningGuide/Procedures/Procedures.html

Slide 48

Slide 48 text

Make it look nicer

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

ANSI escape sequences String sequences Perform operations Unix terminals Windows 10+

Slide 52

Slide 52 text

"Hello, world!" Output print("Hello, world!")

Slide 53

Slide 53 text

"Hello, world!" Output print("\u{1B}[31mHello, world!")

Slide 54

Slide 54 text

print("\u{1B}[1;31mHello, world!") "Hello, world!" Output

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

Do it yourself https://github.com/pakLebah/ANSITerminal Don ’ t!

Slide 57

Slide 57 text

print("Hello, world!") "Hello, world!" Output

Slide 58

Slide 58 text

import ANSITerminal print("Hello, world!") "Hello, world!" Output

Slide 59

Slide 59 text

import ANSITerminal print("Hello, world!".red) "Hello, world!" Output

Slide 60

Slide 60 text

import ANSITerminal print("Hello, world!".red.bold) "Hello, world!" Output

Slide 61

Slide 61 text

⚠ Something to consider

Slide 62

Slide 62 text

It’s not you, it’s Xcode!

Slide 63

Slide 63 text

Do it yourself https://github.com/dominicegginton/spinner Don ’ t! volume II

Slide 64

Slide 64 text

import MusicKit import ArgumentParser @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: " + song.title) print("Artist: " + song.artistName) print("Album: " + song.albumTitle!) print("Genres: " + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 65

Slide 65 text

import MusicKit import ArgumentParser import Spinner @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: " + song.title) print("Artist: " + song.artistName) print("Album: " + song.albumTitle!) print("Genres: " + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 66

Slide 66 text

import MusicKit import ArgumentParser import Spinner @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let spinner = Spinner(.dots, "Loading music results", color: .green) spinner.start() let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() spinner.stop() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: " + song.title) print("Artist: " + song.artistName) print("Album: " + song.albumTitle!) print("Genres: " + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 67

Slide 67 text

import MusicKit import ArgumentParser import Spinner import ANSITerminal @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let spinner = Spinner(.dots, "Loading music results", color: .green) spinner.start() let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() spinner.stop() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: " + song.title) print("Artist: " + song.artistName) print("Album: " + song.albumTitle!) print("Genres: " + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 68

Slide 68 text

import MusicKit import ArgumentParser import Spinner import ANSITerminal @main struct Musicli: AsyncParsableCommand { func run() async throws { guard await isAppAuthorised() else { return } print("Enter the name of the song you'd like to search for . .. ") guard let query = readLine() else { return } let spinner = Spinner(.dots, "Loading music results", color: .green) spinner.start() let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() spinner.stop() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: ".bold + song.title) print("Artist: ".bold + song.artistName) print("Album: ".bold + song.albumTitle!) print("Genres: ".bold + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

https://github.com/matteocrippa/awesome-swift#command-line

Slide 71

Slide 71 text

SwiftTUI https://github.com/rensbreur/SwiftTUI

Slide 72

Slide 72 text

Going the extra mile

Slide 73

Slide 73 text

import ArgumentParser import Spinner import MusicKit import ANSITerminal struct Search: AsyncParsableCommand { @Argument(help: "The search parameter used to find a song") var searchQuery: String? func run() async throws { guard await isAppAuthorised(), let query = askUserIfNeeded() else { return } let spinner = Spinner(.dots, "Loading music results", color: .green) spinner.start() let request = MusicCatalogSearchRequest(term: query, types: [Song.self]) let searchResponse = try await request.response() spinner.stop() print("Search results for: '\(query)'") for song in searchResponse.songs { print("Title: ".bold + song.title) print("Artist: ".bold + song.artistName) print("Album: ".bold + song.albumTitle!) print("Genres: ".bold + song.genreNames.joined(separator: ", ")) print("") } } }

Slide 74

Slide 74 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { static var configuration = CommandConfiguration( subcommands: [Search.self], defaultSubcommand: Search.self ) }

Slide 75

Slide 75 text

import MusicKit import ArgumentParser struct Display: AsyncParsableCommand { func run() async throws { } }

Slide 76

Slide 76 text

import MusicKit import ArgumentParser struct Display: AsyncParsableCommand { @Argument(help: "The song you'd like to display information for") var song: String func run() async throws { } }

Slide 77

Slide 77 text

import MusicKit import ArgumentParser struct Display: AsyncParsableCommand { @Argument(help: "The song you'd like to display information for") var song: String func run() async throws { let request = MusicCatalogSearchRequest(term: song, types: [Song.self]) guard let song = try await request.response().songs.first else { print("Could not find a song to play ... ") return } } }

Slide 78

Slide 78 text

import MusicKit import ArgumentParser struct Display: AsyncParsableCommand { @Argument(help: "The song you'd like to display information for") var song: String func run() async throws { let request = MusicCatalogSearchRequest(term: song, types: [Song.self]) guard let song = try await request.response().songs.first else { print("Could not find a song to play ... ") return } await App(song: song).run() } }

Slide 79

Slide 79 text

import AppKit import MusicKit @MainActor class App { let song: Song let delegate: AppDelegate init(song: Song) { self.song = song self.delegate = AppDelegate(song: song) } func run() { let app = NSApplication.shared app.delegate = delegate app.setActivationPolicy(.regular) app.activate(ignoringOtherApps: true) app.run() } }

Slide 80

Slide 80 text

import AppKit import SwiftUI import MusicKit final class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! let song: Song init(song: Song) { self.song = song } func applicationDidFinishLaunching(_ notification: Notification) { let window = NSWindow( contentRect: .zero, styleMask: [.closable, .resizable, .titled], backing: .buffered, defer: false ) window.contentViewController = NSHostingController( rootView: SongView(song: song) ) window.makeKey() window.center() window.orderFrontRegardless() window.title = "🎶 \(song.title) - \(song.artistName)" self.window = window } }

Slide 81

Slide 81 text

import SwiftUI import MusicKit struct SongView: View { let song: Song var body: some View { ZStack { Color(song.artwork ?. backgroundColor ?? .white) .ignoresSafeArea() VStack(spacing: 8) { AsyncImage(url: song.artwork ?. url(width: 400, height: 400)) { image in image .resizable() .frame(width: 400, height: 400) .clipShape(RoundedRectangle(cornerRadius: 20)) } placeholder: { Text("Loading . .. ") } Text(song.title) .font(.largeTitle) .fontWeight(.heavy) .fontDesign(.rounded) Text("\(song.artistName) − \(song.albumTitle ?? "")") .font(.body) .foregroundStyle(Color(cgColor: song.artwork ?. tertiaryTextColor ?? .black)) } .foregroundStyle(Color(song.artwork ? . primaryTextColor ?? .black)) } .frame(width: 600, height: 600) } }

Slide 82

Slide 82 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { static var configuration = CommandConfiguration( subcommands: [Search.self], defaultSubcommand: Search.self ) }

Slide 83

Slide 83 text

import ArgumentParser @main struct Musicli: AsyncParsableCommand { static var configuration = CommandConfiguration( subcommands: [Search.self, Display.self], defaultSubcommand: Search.self ) }

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

Ready to ship? polpiella.dev Homebrew, GitHub + CI/CD

Slide 86

Slide 86 text

Build tools!

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

Find me online! bento.me/pol @polpielladev