Am just starting to use SQLite in Swift and am running into a declaration problem. I would like to wrap everything in one class that I can then call methods on.
My problem is I don’t know how to declare db so that when I do call Connect, it can be filled in an always be available while the class exists. I could call connect at the init, but I don’t want to call Connect until I need it. When I code it as below I get the following error:
Return from initializer without initializing all stored properties
class MySQL {
var db : Connection
var dbPath : String
init() {
dbPath = getDocumentsDirectory().absoluteString + "db.sqlite3"
}
func open(){
do{
db = try Connection(dbPath)}
catch{}
let users = Table("users")
print(users)
}
}
2
Answers
You probably want to use lazy property.
More information you can read from official docs.
Absolutely right! Don’t do anything like that in
init
.Just rewrite your declaration to make the Connection
nil
, precisely as you suggested:The consequence is that whenever you talk to
self.db
from now on, except in order set it, you will have to check whether it isnil
. You can use Optional chaining to do that painlessly. You could avoid that by declaringdb
asConnection!
instead ofConnection?
but that risks a later crash and I can’t recommend it.