我想在详细信息项不为零时显示详细信息表,而不需要额外的布尔值 @State 变量:
.sheet(isPresented: $optionalDetailItem.notNilBinding()) {
Text("Details")
}
这是我当前的代码。如何使其适用于不可发送的项目?如果我删除可发送要求,我会收到错误
Capture of 'self' with non-sendable type 'Binding<Optional<T>>' in a '@Sendable' closure
。
@available(iOS 13.0, macOS 10.15, *)
public extension Binding {
/// Careful, never set this to `true`.
func notNilBinding<T: Sendable>() -> Binding<Bool> where Value == Optional<T> {
Binding<Bool>(
get: { self.wrappedValue != nil },
set: { newValue in
if !newValue {
wrappedValue = nil
} else {
// In this context we cannot not know what to set `wrappedValue` to.
fatalError("This must not be set to `true`.")
}
}
)
}
}
如果数据不为nil,您可以使用此方法sheet(item:onDismiss:content:)来显示sheet。
@State private var optionalDetailItem: DetailItem?
当OptionalDetailItem的值设置为非nil时,将显示sheet
.sheet(isPresented: $optionalDetailItem) {
Text("Details")
}