You need to enable JavaScript to run this app. SwiftUI报Missing argument for parameter 'user'错误 实例化HomeView求助
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI报Missing argument for parameter 'user'错误 实例化HomeView求助

提问内容

我在ProfileViewModel中定义了常量let user: UserModel,对应的UserModel已在文件中遵循Identifiable协议,且已经在ProfileViewModel的初始化方法中完成了user: UserModel的赋值。
我在HomeView中添加了常量let profileVM: ProfileViewModel,原本是想通过profileVM.user.profileImageURL获取用户头像地址。但在MainView中,需要根据用户登录、注册状态加载HomeView实例时,IDE提示我必须在HomeView()的调用位置传入profileVM和user常量,直接运行App就会抛出错误。

我的相关代码如下:

MainView.swift(IDE提示需要传参的报错位置)

import UIKit
import SwiftUI
import Firebase

struct MainView: View {
    @EnvironmentObject var authViewModel: AuthViewModel
    @AppStorage("current_status") var profileRegistered = false
    
    var body: some View {
        ZStack{
            if authViewModel.session != nil && authViewModel.profileRegistered == false {
                RegisterView()
            } else {
                HomeView()
            }
           
            if authViewModel.session == nil {
                NavigationView{
                    Login()
                        .navigationBarHidden(true)
                        .navigationBarBackButtonHidden(true)
                }
            }
        }
    }
}

HomeView.swift(顶部核心实现代码)

import SwiftUI
import Firebase
import Kingfisher

struct HomeView: View {
    @State var showProfile: Bool = false
    @State var userSearch: Bool = false
    @EnvironmentObject var authViewModel: AuthViewModel
    let profileVM: ProfileViewModel
        
    var body: some View {
        VStack {
            HStack(alignment: .top) {
                // 跳转至社区用户搜索页按钮
                Button(action: { self.userSearch.toggle() }) {
                    Image(systemName: "person.crop.circle.badge.plus")
                        .font(.system(size: 30))
                        .foregroundColor(.black)
                }.fullScreenCover(isPresented: $userSearch) {
                    UserSearch()
                }
                
                Spacer()
                // 跳转至个人主页按钮
                Button(action: { self.showProfile.toggle() }) {
                     KFImage(URL(string: profileVM.user.profileImageURL))
                        .renderingMode(.original)
                        .resizable()
                        .frame(width: 36, height: 36)
                        .clipShape(Circle())
                }.fullScreenCover(isPresented: $showProfile) {
                    MyProfileView()
                }
            }
            .padding(.horizontal)
            .padding(.top, 15)
            
            Button(action: {
                // 退出登录逻辑
               authViewModel.signOut()
            }, label: {
                Text("LogOut")
                    .fontWeight(.heavy)
            })
            
            Spacer()
        }
    }
}

注:原代码粘贴时存在结构错乱,已调整为可编译的正确结构

ProfileViewModel.swift

import SwiftUI

class ProfileViewModel: ObservableObject {
    // MARK: - 属性
    @Published var isFollowed: Bool = false
    let user: UserModel
    
    // MARK: - 初始化方法
    init(user: UserModel) {
        self.user = user
        // 应用关闭后仍持久化保存当前用户的关注状态
        checkIfUserIsFollowed()
    }
    
    // MARK: - 类方法
    // 关注用户
    func follow() -> Void {
        // 获取当前登录用户ID
        guard let currentUid = FIREBASE_AUTH.currentUser?.uid else { return }
        let followingRef = COLLECTION_FOLLOWING_FIRESTORE.document(currentUid).collection("user-following")
        let followersRef = COLLECTION_FOLLOWERS_FIRESTORE.document(currentUid).collection("user-followers")
        
        // 当前用户关注目标用户时,更新关注列表
        followingRef.document(user.id).setData([ : ]) { _ in
            // 同步更新目标用户的粉丝列表,记录当前用户为粉丝
            followersRef.document(currentUid).setData([ : ]) { _ in
                self.isFollowed = true
                print("DEBUG: Followed: @\(self.user.lastname)...")
            }
        }
    }
    
    // 取消关注用户
    func unFollow() -> Void {
        // 获取当前登录用户ID
        guard let currentUid = FIREBASE_AUTH.currentUser?.uid else { return }
        let followingRef = COLLECTION_FOLLOWING_FIRESTORE.document(currentUid).collection("user-following")
        let followersRef = COLLECTION_FOLLOWERS_FIRESTORE.document(currentUid).collection("user-followers")
        
        followingRef.document(user.id).delete { _ in
            followersRef.document(currentUid).delete { _ in
                self.isFollowed = false
                print("DEBUG: UnFollowed: @\(self.user.lastname)...")
            }
        }
    }
}

extension ProfileViewModel {
    // 检查目标用户是否已被当前用户关注
    func checkIfUserIsFollowed() -> Void {
        guard let currentUid = FIREBASE_AUTH.currentUser?.uid else { return }
        let followingRef = COLLECTION_FOLLOWING_FIRESTORE.document(currentUid).collection("user-following")
        
        followingRef.document(user.id).getDocument { snapShot, _ in
            guard let isFollowed = snapShot?.exists else { return }
            self.isFollowed = isFollowed
        }
    }
}

UserModel.swift

import SwiftUI
import Firebase

struct UserModel: Identifiable {
    // MARK: - 属性
    var id = UUID().uuidString
    let headline: String
    let profileImageURL: String
    let firstname: String
    let lastname: String
    let email: String
    let bio: String
    
    var isCurrentUser: Bool {
        Auth.auth().currentUser?.uid == self.id
    }
    
    // MARK: - 初始化方法
    init(dictionary: [String : Any]) {
        typealias k = RegistrationKeys
        id = dictionary[k.uidKey] as? String ?? ""
        headline = dictionary[k.headline] as? String ?? ""
        profileImageURL = dictionary[k.profileImageURLKey] as? String ?? ""
        firstname = dictionary[k.firstname] as? String ?? ""
        lastname = dictionary[k.lastname] as? String ?? ""
        email = dictionary[k.emailKey] as? String ?? ""
        bio = dictionary[k.bioKey] as? String ?? ""
    }
}

RegistrationKeys.swift

import Foundation

struct RegistrationKeys: Hashable {
    static let emailKey = "email"
    static let headline = "headline"
    static let firstname = "firstname"
    static let lastname = "lastname"
    static let profileImageURLKey = "profileImageURL"
    static let bioKey = "bio"
    static let uidKey = "uid"
}

用户注册时上传UserModel数据到Firebase的实现代码

// MARK: - 用户注册逻辑
func registerUser(firstname: String, lastname: String, headline: String, bio: String, profileImage: UIImage) -> Void {
    // 1. 上传用户头像
    guard let imageData = profileImage.jpegData(compressionQuality: 0.3) else { return }
    // 为上传的头像生成唯一标识
    let filename = NSUUID().uuidString
    let storageRef = Storage.storage().reference().child(filename)
    
    storageRef.putData(imageData, metadata: nil) { _, error in
        if let error = error {
            print("\nDEBUG: {!!!} [ERROR] 头像上传失败: \(error.localizedDescription) {!!!}")
            return
        }
        print("DEBUG: 用户头像上传成功...")
        
        // 获取已上传头像的访问地址
        storageRef.downloadURL { url, _ in
            guard let profileImageURL = url?.absoluteString else { return }
            let uid = FIREBASE_AUTH.currentUser!.uid
            
            // 4. 构造包含键值对的用户数据字典
            typealias k = RegistrationKeys
            let data: [String : String] = [
                k.uidKey: uid,
                k.headline : headline,
                k.firstname : firstname,
                k.lastname : lastname,
                k.bioKey : bio,
                k.profileImageURLKey : profileImageURL
            ]
            
            // 将用户数据上传至Firestore
            self.uploadCollectionToFirestore(
                data: data,
                uid: uid,
                firstname: firstname,
                lastname: lastname,
                headline: headline,
                bio: bio
            )
            
            withAnimation{self.profileRegistered = true}
        }
    }
}

extension AuthViewModel {
    // MARK: - 上传用户数据到Firestore集合
    fileprivate func uploadCollectionToFirestore(data: [String : String], uid: String,
                                                 firstname: String, lastname: String, headline: String,
                                                 bio: String) {
        isLoading = true
        COLLECTION_USERS_FIRESTORE.document(uid).setData(data) { (err) in
            if err != nil{
                self.isLoading = false
                return
            }
            print("DEBUG: 用户注册成功\n")
        }
    }
}

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 17:54:03