Skip to content

Instantly share code, notes, and snippets.

@lukaskollmer
Created June 15, 2025 20:26
Show Gist options
  • Save lukaskollmer/5ca7eb3887dde3f3faba2cab29e8bc36 to your computer and use it in GitHub Desktop.
Save lukaskollmer/5ca7eb3887dde3f3faba2cab29e8bc36 to your computer and use it in GitHub Desktop.
View.sheet(item:id:onDismiss:content)
//
// This source file is part of the Stanford Spezi open-source project
//
// SPDX-FileCopyrightText: 2025 Stanford University and the project authors (see CONTRIBUTORS.md)
//
// SPDX-License-Identifier: MIT
//
import Foundation
import SwiftUI
private struct IdentifiableAdaptor<Value, ID: Hashable>: Identifiable {
let value: Value
private let _id: (Value) -> ID
var id: ID { _id(value) }
init(value: Value, id: @escaping (Value) -> ID) {
self.value = value
self._id = id
}
}
extension View {
public func sheet<Item, ID: Hashable>(
item: Binding<Item?>,
id: @escaping (Item) -> ID,
onDismiss: (@MainActor () -> Void)? = nil,
@ViewBuilder content: @MainActor @escaping (Item) -> some View
) -> some View {
let binding = Binding<IdentifiableAdaptor<Item, ID>?> {
if let item = item.wrappedValue {
IdentifiableAdaptor(value: item, id: id)
} else {
nil
}
} set: { newValue in
if let newValue {
item.wrappedValue = newValue.value
} else {
item.wrappedValue = nil
}
}
return self.sheet(item: binding, onDismiss: onDismiss) { item in
content(item.value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment