在一个ObservableObject类中是否可以有两个init?

huangapple go评论57阅读模式
英文:

Is it possible to have two init in an ObservableObject class?

问题

以下是您要翻译的内容:

我已经创建了一个名为 `ObservableObject` 的对象类,并且需要创建两个初始化方法,一个带有字符串参数,另一个不带参数。

class DictionaryModel: ObservableObject {
    @Published var dbName: String = ""
    private var dbQueue: DatabaseQueue!
    var localDBFile: String

    // 这个 `init` 方法可以正常工作:

    init(_ localDBName: String) {
        self.localDBFile = localDBName
        var config = Configuration()
        config.readonly = false
        guard let dbPath = Bundle.main.path(forResource: localDBName, ofType: "sqlite") else { return }
        do {
            self.dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
        } catch let error {
            print(error.localizedDescription)
        }
    }
}

对于第二个初始化方法,我需要在不同情况下更改 `@Published var dbName`,例如当用户选择另一个数据库时。我希望这个更改 `dbName` 会影响所有视图,比如书签、搜索等等。

init() {
    var config = Configuration()
    config.readonly = false
    let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let dbPath = documentDirectoryURL.appendingPathComponent("\(dbName).sqlite").path

    do {
        self.dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
    } catch let error {
        print(error.localizedDescription)
    }
    fetchBookmarks()
}

我一直收到这个错误信息:`在初始化所有存储属性之前,'self' 在属性访问 'dbName' 中被使用`。是否有办法在一个类中有两个初始化方法,一个带有参数,另一个没有?

请注意,我已将代码部分保留在原文中。

英文:

I have created an ObservableObject object class, and I need to create 2 inits one with passing a string parameter and another without passing.

class DictionaryModel: ObservableObject {
    @Published var dbName: String = ""
	private var dbQueue: DatabaseQueue!
	var localDBFile: String

//this `init` works fine:

init(_ localDBName: String) {
		self.localDBFile = localDBName
		var config = Configuration()
		config.readonly = false
		guard let dbPath = Bundle.main.path(forResource: localDBName, ofType: "sqlite") else { return }
		do {
			self.dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
		} catch let error {
			print(error.localizedDescription)
		}
	}

}

for the second init I need to change @Published var dbName on different occasions, for example when user choose another database. I need this changing dbName to affects on all views like bookmark, searching and etc..

init() {
	var config = Configuration()
	config.readonly = false
	let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
	let dbPath = documentDirectoryURL.appendingPathComponent("\(dbName).sqlite").path
	
	do {
		self.dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
	} catch let error {
		print(error.localizedDescription)
	}
	fetchBookmarks()
}

I keep getting this error self' used in property access 'dbName' before all stored properties are initialized. Is there any way to have two inits in one class one with passing parameter and another without any?

答案1

得分: 1

绝对可以。但你不能违反规则:正如错误消息告诉你的那样,你不能在初始化所有存储属性之前访问 dbName。那么有哪些存储属性呢?localDBFile。你 必须localDBFile 设置为 某些内容 — 而你并没有这样做。即使你只是将它设置为空字符串,你也 必须 将它设置为 某些内容

此外,你的声明 private var dbQueue: DatabaseQueue! 是一个非常糟糕的主意。感叹号意味着“让我崩溃”。这是一个等待发生的意外。

英文:

> Is there any way to have two inits in one class one with passing parameter and another without any?

Absolutely. But you cannot violate the rules: you cannot, as the error message tells you, "access dbName before all stored properties are initialized." And what stored properties are there? localDBFile. You must set localDBFile to something — and you are not doing that. Even if you just set it to an empty string, you must set it to something.

Moreover, your declaration private var dbQueue: DatabaseQueue! is a really bad idea. Exclamation mark means "crash me". This is an accident waiting to happen.

huangapple
  • 本文由 发表于 2023年3月4日 01:40:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定