在使用所需的便利init进行解码时,如何解决“调用中的额外参数?” []:<

问题描述 投票:0回答:1
我对应用程序开发还比较陌生,正在尝试为使用SwiftUI编写的作业管理应用程序增加持久性。我正在“ UserData”类中实现NSCoding,并且能够毫无问题地创建编码函数,但是在设置解码函数后,我在self.init上收到错误消息“调用中的额外参数'assignments'”( )行。我的代码到底有什么问题?

class UserData: NSObject, NSCoding, ObservableObject { // MARK:- Properties @Published var assignments: [Assignment] @Published var courses: [Course] = [] @Published var username: String = "" @Published var appState: AppState = AppState(willPresentSplashScreen: false) ... // MARK:- NSCoding func encode(with coder: NSCoder) { coder.encode(assignments, forKey: PropertyKey.assignments) coder.encode(courses, forKey: PropertyKey.courses) coder.encode(username, forKey: PropertyKey.username) coder.encode(appState, forKey: PropertyKey.appState) } required convenience init?(coder decoder: NSCoder) { let assignments = decoder.decodeObject(forKey: PropertyKey.assignments) as? [Assignment] let courses = decoder.decodeObject(forKey: PropertyKey.courses) as? [Course] let username = decoder.decodeObject(forKey: PropertyKey.username) as? String let appState = decoder.decodeObject(forKey: PropertyKey.appState) as? AppState self.init(assignments: assignments, courses: courses, username: username, appState: appState) } }

我对应用程序开发还比较陌生,正在尝试为使用SwiftUI编写的作业管理应用程序增加持久性。我在“ UserData”类中实现了NSCoding,并且能够创建...
ios swift nscoding
1个回答
0
投票
init(assignments: [Assignment], courses: [Course], username: String, appState: AppState) { self.assignments = assignments self.courses = courses self.username = username self.appState = appState }

这将给您一个错误,因为您有可选参数,并且初始化程序不希望有可选参数,所以您需要解包从init?(coder decoder: NSCoder)传递来的参数。

init?(coder decoder: NSCoder)是失败的初始化程序,因此如果一切都不正确,则可以返回nil

required convenience init?(coder decoder: NSCoder) {

        guard let assignments = decoder.decodeObject(forKey: PropertyKey.assignments) as? [Assignment],
            let courses = decoder.decodeObject(forKey: PropertyKey.courses) as? [Course],
            let username = decoder.decodeObject(forKey: PropertyKey.username) as? String,
            let appState = decoder.decodeObject(forKey: PropertyKey.appState) as? AppState else {
                return nil
        }

        self.init(assignments: assignments, courses: courses, username: username, appState: appState)
}

我可能会摆脱分配给coursesusernameappState的默认值-您不需要它们,因为这些值将来自初始化程序

© www.soinside.com 2019 - 2024. All rights reserved.