本文介绍了SwiftUI:如何在`$` 可绑定对象运算符之前使用`!` 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法对 Bindable $
对象使用逻辑非 !
运算符.
这是我想要的场景-
struct ContentView: View {
@State private var isLoggedIn:Bool = true
var body: some View {
Text("Root View")
.sheet(isPresented: !self.$isLoggedIn) {
SignInView()
}
.onAppear { self.performAuthentication() }
}
}
登录视图应该在我通过某些按钮操作设置 isLoggedIn = false
后立即显示.为此,我必须在 $
之前使用逻辑非运算符.
Sign In View should present as soon as I set isLoggedIn = false
by some button action. For which I have to use logical not operator before $
.
编译器错误:无法将绑定"类型的值转换为预期的参数类型 'Bool'
我怎样才能做到这一点?
How can I achieve this?
推荐答案
正如我在对问题的评论中所说,有针对 SwiftUI 发布的方法: 将 Binding 转换为另一个 Binding.但是,如果您希望将其明确作为运算符,则可以使用以下内容(经过测试并适用于 Xcode 11.2)
As I said in comment to question there were approach posted for SwiftUI: transform Binding into another Binding. If you, however, want to have it explicitly as operator, you can use the following (tested & works with Xcode 11.2)
extension Binding where Value == Bool {
static prefix func !(_ lhs: Binding<Bool>) -> Binding<Bool> {
return Binding<Bool>(get:{ !lhs.wrappedValue },
set: { lhs.wrappedValue = !$0})
}
}
这篇关于SwiftUI:如何在`$` 可绑定对象运算符之前使用`!` 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!