Home > Software engineering >  Cannot assign value of type 'Binding<Bool>' to type 'Bool'
Cannot assign value of type 'Binding<Bool>' to type 'Bool'

Time:11-29

I'm having trouble with initialising a Bool, it keeps giving me errors and I can't seem to find the solution. The error I'm getting with the below code is "Cannot assign value of type 'Binding' to type 'Bool'"

Any ideas?

struct ProfileView: View {
@ObservedObject var viewModel: ProfileViewModel
@Binding var isFollowed: Bool

init(user: User) {
    self.viewModel = ProfileViewModel(user: user)
    // error below
    self.isFollowed = $isFollowed
    // error above
}

CodePudding user response:

I'm not clear what you want to do, but the $ notation is when you pass a property wrapper, such as @State or @Published to someone else.

For example if you want to initialize your @Binding property with some value passed on initialization:

First you need a corresponding argument in the init, and you initialize its value by using the "special" syntax with underscore:

init(...,
     isFollowed: Binding<Bool>) {
    
    // This is how binding is initialized
    self._isFollowed = isFollowed

Now we assume that some other class or struct (lets call it Other), which has some sort of state or published property:

@Published var isProfileFollowed = false

So from that Other class/struct you can create an instance of ProfileView like this:

ProfileView(...,
            isFollowed: $isProfileFollowed)

That is not just passing a current value of isProfileFollowed, but binding a isFollowed of ProfileView to isProfileFollowed of class/struct Other, so that any change in isProfileFollowed is also visible to a binded property isFollowed.

So this is just an explanation of what's not working.

  • Related