Can't create binding in TextField - 'cannot find $social' in scope'

Viewed 849

I can't create a binding with my 'username' property - Xcode gives me the error 'cannot find $social in scope'. Here is some of the essential code:

My problematic view:

struct ProfileSetter: View {
    @Binding var profile: Profile
    
    var body: some View {
        ForEach(profile.socials, id: \.id) { social in
            TextField(social.medium.rawValue, text: $social.username) //-> cannot find $social in scope
        }
    }
}

Its parent:

struct ProfileView: View {
    @StateObject private var viewModel = ViewModel()
    
    var body: some View {
        ProfileSetter(profile: $viewModel.myProfile)
    }
}

The simplified view model:

class ViewModel: ObservableObject {
    @Published var myProfile = Profile(socials: [//multiple instances of Social])
}

And finally, the models:

struct Profile {
    // other properties
    var socials: [Social]
}

struct Social {
    // other properties
    var username: String
}

Replacing the text field with Text(social.username) works fine, so creating the binding seems to be the problem.

1 Answers

You cannot bind directly to value, you should do it via parent object, like

ForEach(profile.socials.indices, id: \.self) { index in
    TextField(profile.socials[index].medium.rawValue, 
        text: $profile.socials[index].username)
}
Related