Swift 用户结构错误:从初始化器返回而不初始化所有存储的属性

问题描述 投票:0回答:1

我正在构建一个个人资料页面,并且尝试在用户注销后保存个人资料图片。 这是我的用户结构:

struct User: Codable {
    var uid: String
    var email: String
    var firstName: String
    var lastName: String
    var signUpDate: Date
    var bio: String
    var interests: [String]
    var profilePictureURL: URL?
}

这是我的个人资料页面视图(导致错误的部分):

struct ProfileView: View {
    @ObservedObject var userViewModel: UserViewModel
    @State private var bio = UserDefaults.standard.string(forKey: "bio") ?? "Car enthusiast | Eco-friendly driver | Developer"
    @State private var interests = UserDefaults.standard.string(forKey: "interests") ?? "Travel, Coding, Green Living"
    @State private var isEditingBio = false
    @State private var isEditingInterests = false
    @State private var isEditingProfile = false
    @State private var selectedImage: UIImage? {
        didSet {
            if let selectedImage = selectedImage {
                if let imageData = selectedImage.jpegData(compressionQuality: 0.8) {
                    UserDefaults.standard.set(imageData, forKey: "profileImage")
                }
            }
        }
    }
    init(userViewModel: UserViewModel) {
           self.userViewModel = userViewModel
       }

    init() {
        if let imageData = UserDefaults.standard.data(forKey: "profileImage"),
           let image = UIImage(data: imageData) {
            _selectedImage = State(initialValue: image)
        } else {
            // Initialize with a default image if no profile image is found
            _selectedImage = State(initialValue: UIImage(systemName: "person.circle.fill")!)
        }
    }

错误发生在第二个init语句处,错误是: 从初始化器返回而不初始化所有存储的属性

我尝试过查看有关堆栈溢出的其他解决方案,但我不太理解它们。我还尝试通过输入 user:user 参数来初始化其他值,然后对其他属性执行 let uid=user.uid 等等。我对如何解决这个问题感到困惑。谢谢您的帮助!

swift struct
1个回答
0
投票

second init
中显示错误是因为您没有在第二个
userViewModel
中初始化
init
。因此,您需要做的就是将代码从
second init
移动到
init(userViewModel: 
:

init(userViewModel: UserViewModel) {
    self.userViewModel = userViewModel
    if let imageData = UserDefaults.standard.data(forKey: "profileImage"),
       let image = UIImage(data: imageData) {
        _selectedImage = State(initialValue: image)
    } else {
        // Initialize with a default image if no profile image is found
        _selectedImage = State(initialValue: UIImage(systemName: "person.circle.fill")!)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.