With the example of GRDB, a lightweight sqlite wrapper:
class DbManager {
static let sharedInstance = DbManager()
var dbPath: String! <--- !!!
var dbQueue: DatabaseQueue!
private init() {
do {
dbQueue = try connectToDatabase()
try createTable()
} catch {
print(error)
}
}
}
Then use it like this:
try DbManager.sharedInstance.dbQueue.write {...}
The catch is to use the exclamation mark while creating class variables. Otherwise you’ll get the error:
Variable 'self.dbQueue' used before being initialized
The use of ?
is widely used in various languages to describe an optional value, as in:
obj?.attr
Indicating that we’ll only try to access attr
on obj
if it exists. The use of !
however is a fun one. It declares that we’re 100% certain this variable is not nil. If it is nil we’ll get into runtime errors, so make sure it isn’t.