Home > Software design >  Cannot find ... in scope
Cannot find ... in scope

Time:01-06

I want the string in text field take the values of name of Player [0]. I try this and I have this error "Cannot find '$PlayerList' in scope".

import SwiftUI

class PlayerList : ObservableObject {
    @Published var  Players = [
        Player(name: ""),
        Player(name: ""),
    ]
    init() {
    }
}

struct Player : Identifiable {
    var name : String
    var id = UUID()
}
struct ViewJouer: View {

    @StateObject var viewModel: PlayerList = PlayerList()

        var body: some View {
            VStack {
                TextField("Player 1", text: $PlayerList.Players[0].name)
        }
    }
}
struct ViewJouer_Previews: PreviewProvider {
    static var previews: some View {
        ViewJouer()
    }
}

CodePudding user response:

You don't have the PlayerList variable in the view, you called it viewModel.

Moreover, please use the Swift notation: variables start with lowercase letters.

Here's the corrected code:

import SwiftUI

class PlayerList : ObservableObject {

    // Variables start with lowercase letter
    @Published var players = [
        Player(name: ""),
        Player(name: ""),
    ]
}

struct Player : Identifiable {
    var name : String

    // If you don't change the id, make it a constant
    let id = UUID()
}
struct ViewJouer: View {

    // Better make your local variables private
    @StateObject private var viewModel = PlayerList()

        var body: some View {

            // The player list is part of the view model
            VStack {
                TextField("Player 1", text: $viewModel.players[0].name)
        }
    }
}
struct ViewJouer_Previews: PreviewProvider {
    static var previews: some View {
        ViewJouer()
    }
}
  • Related