0

I'm working on a SwiftUI app and encountered an error: Cannot find 'UserViewModel' in scope when trying to use my UserViewModel in HomeScreen`(line of code 11). I've ensured that the UserViewModel class is defined, and I'm importing SwiftUI in both files.

Here's the setup: UserViewModel.swift

import SwiftUI

class UserViewModel: ObservableObject {
    @Published var users: [User] = []
    @Published var errorMessage: String?
    
    func fetchUsers(completion: @escaping () -> Void = {}) {
        UserService.shared.fetchUsers { result in
            DispatchQueue.main.async {
                switch result {
                case .success(let users):
                    self.users = users.sorted { $0.id < $1.id }
                    completion()
                case .failure(let error):
                    self.errorMessage = error.localizedDescription
                }
            }
        }
    }
    
    func addUser(user: User) {
        if !users.contains(where: { $0.id == user.id }) {
            users.append(user)
        }
    }
}

HomeScreen.swift

import SwiftUI

struct HomeScreen: View {
    var currentUser: User
    
    @StateObject private var viewModel = UserViewModel()
    @State private var selectedUser: User?
    @State private var showAlert = false
    @State private var navigateToGameScreen = false
    
    var body: some View {
        NavigationView {
            VStack {
                HStack {
                    Spacer()
                    Text("Welcome, \(currentUser.firstName) \(currentUser.lastName)")
                        .padding()
                }
                
                VStack {
                    Text("Users")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                        .padding(.bottom, 10)
                    
                    if let errorMessage = viewModel.errorMessage {
                        Text(errorMessage)
                            .foregroundColor(.red)
                            .padding()
                    } else {
                        List(viewModel.users) { user in
                            HStack {
                                Text("\(user.firstName) \(user.lastName)")
                                Spacer()
                                if currentUser.id != user.id {
                                    Button(action: {
                                        selectedUser = user
                                        showAlert = true
                                    }) {
                                        Text("Play")
                                            .foregroundColor(.blue)
                                    }
                                } else {
                                    Text("You")
                                        .foregroundColor(.gray)
                                }
                            }
                        }
                    }
                }
                .padding()
                .navigationTitle("")
                .navigationBarHidden(true)
            }
            .onAppear {
                viewModel.fetchUsers {
                    viewModel.addUser(user: currentUser)
                }
            }
            .alert(isPresented: $showAlert) {
                Alert(
                    title: Text("Play Game"),
                    message: Text("Do you want to play guess name with \(selectedUser?.username ?? "")?"),
                    primaryButton: .default(Text("Yay!"), action: {
                        navigateToGameScreen = true
                    }),
                    secondaryButton: .cancel(Text("Naah"))
                )
            }
            .background(
                NavigationLink(destination: GameScreen(opponentUsername: selectedUser?.username ?? "", loggedInUser: currentUser), isActive: $navigateToGameScreen) {
                    EmptyView()
                }
                .hidden()
            )
        }
        .navigationBarBackButtonHidden(true) // Hide back button
    }
}

struct HomeScreen_Previews: PreviewProvider {
    static var previews: some View {
        HomeScreen(currentUser: User(id: 1, firstName: "John", lastName: "Doe", age: 30, username: "johndoe", email: "[email protected]"))
    }
}

What I've Tried Import Statements: Verified that both files have import SwiftUI.

File Locations: Ensured that both files are included in the same target and are located within the same group in Xcode.

Build and Clean: Tried cleaning the project and rebuilding it.

Reimport: Tried adding import Foundation in UserViewModel.swift.

Problem Despite these checks, Xcode still shows Cannot find 'UserViewModel' in scope when trying to instantiate UserViewModel in HomeScreen.

2
  • Did you check the target membership? Commented Aug 1, 2024 at 15:28
  • @sonle Yes I checked it, target membership is checked only at my app name(not tests, and UI Tests) Commented Aug 1, 2024 at 15:31

1 Answer 1

0

The solution is in Xcode version. I just switched on previous version of Xcode and now it works!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.