Skip to content

Instantly share code, notes, and snippets.

View macguru's full-sized avatar

Max Seelemann macguru

View GitHub Profile
@macguru
macguru / ScopedTask.swift
Last active May 17, 2026 21:59
ScopedTask: A wrapper around Task that auto-cancels when going out of scope.
/// A task that is cancelled if goes out of scope, i.e. the last reference on it has been discarded.
public final class ScopedTask<Success: Sendable, Failure: Error>: Sendable {
/// The underlying task
let wrapped: Task<Success, Failure>
/// Wraps a task into a scoped task.
init(wrapping task: Task<Success, Failure>) {
wrapped = task
}
@macguru
macguru / TaskCancellationHandler.swift
Last active November 9, 2025 09:01
Combines withTaskCancellationHandler with a CheckedContinuation.
import Synchronization
func untilCancelled() async {
print("1")
let mutex: Mutex<CheckedContinuation<Void, Never>?> = .init(nil)
await withTaskCancellationHandler {
print("2")
await withCheckedContinuation { continuation in
print("3")
@macguru
macguru / Thing.swift
Created February 16, 2026 22:21
AsyncStream based observation sample
import Foundation
import Synchronization
class Thing {
var value: Int = 0
var observers: [UUID: AsyncStream<Int>.Continuation] = [:]
func nextValue() async throws -> Int {
let id = UUID()
@macguru
macguru / UncertainFuture.swift
Created February 16, 2026 22:55
Helper for implementing observations using cancellable async/await functions
import Foundation
import Synchronization
/// Synchronization mechanism to support cooperative and cancellable waiting on a value that _might_ become available _at some point in the future_.
public final class UncertainFuture<Value: Sendable>: Sendable {
/// Initializes a new uncertain future.
public init() {}
/// Return the passed value to all currently suspended callers waiting for ``value``.
public func complete(_ value: Value) {
@macguru
macguru / FocusTest.swift
Created June 5, 2026 10:26
SwiftUI .focusedValue() test with sheet presentation
import SwiftUI
@main
struct focustestApp: App {
@FocusedValue(\.color) var focusedColor: String?
var body: some Scene {
WindowGroup {
ContentView()
}