How to use "@Binding"

Hi,

I've started a small IOS app development using Swift and SwiftUI and have encountered a problem I cannot seem to find a solution for.

I want to do have a state value shared between to views and read about "@Binding" which seems to do exactly what I need. Apple also have nice presentation from WWDC2019 showing this feature. The problem is, that the compiler doesn't recognize this.

When I add a line like shown below, to the view, I get the message "Unknown attribute 'Binding'"

@Binding var isPresented : Bool

I'm using Xcode 11.3 so I assume that the compiler is up to date. I started out with a "Single View App" template but fail to see that I could have started out differently.

Any suggestions as to what I'm missing? Is the something that need enabling in Xcode?

Yours,
Jens Christian Rodi Hansen

Try adding import SwiftUI into the file where you use Binding.

1 Like

Thanks for the suggestion.

I already have 'import SwiftUI' in most of the source files, including the one where I try to use @Binding

Other than that. What's your project called like? Don't call it SwiftUI or it will confuse the compiler and you won't be able to import the actual library. And last but not least check your minimal deployment target to be at least iOS 13 or any other OS that introduced SwiftUI.

Right now the project is called Lullaby (just a name for the initial development phase). That should not conflict. I've left the deployment target at 13.2, as set by default when the project was created.

I guess I should try to create a new, very simple project, and see if I can get that working.

1 Like

I finally found the cause of this, thanks to the hint on naming. It was not naming of the project, but rather naming of a class defined by a library I've included for working with a SqLite database. The library SQift has a class called Binding, which is the cause of the conflict.

The solution/workaround is to use "@SwiftUI.Binding" to mark the member. This works. Of course the correct solution would be not having a class in the project called Binding.

The probably means that I never should make a custom class called "State" (and other similar attribute names)...

Thanks a lot for the suggestions. It got me on the right track.

Yours.
Jens Christian Rodi Hansen

2 Likes

I think this is still okay, because there is a way to disambiguate types in Swift, even though it can become tedious in some scenarios. You could also just type alias it typealias _Binding = SwiftUI.Binding.

Using typealias is another solution. I can see that they are global (contrary to C#/.NET), realy nice.

Thanks for pointing that out :slightly_smiling_face:

hey, i have the same problem, but that thing you said, didn't work for me..
i have a ui from swiftUI and now in swift, i used swiftUI, then i want when i pressed a button it's present a UIViewController.
typealias _Binding = SwiftUI.Binding
@_Binding var someThing = Bool
but it doesn't work..
@rodi