Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swiftui

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.

like image 272
PrayForTech Avatar asked Dec 04 '25 17:12

PrayForTech


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)
}
like image 158
Asperi Avatar answered Dec 06 '25 08:12

Asperi