I need to initialize a variable to connect to an SQLite database in Swift. I am using the SQLite.swift library and need to connect to the database with this line:
let db = try Connection("path/to/db.sqlite3")
However, this line by itself will not work because it needs to be surrounded with a try/catch block. Try/catch blocks will not work unless they are defined within methods or functions, so now we have
public func connectToDB() {
do {
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true
).first!
let db = try Connection("\(path)/db.sqlite3")
}
catch {
print("error connecting to database")
}
}
However, this doesn't allow me to access the variable from other methods in the same file, which is what I need to do. Global let declarations also require initialization, so that means it cannot be set globally. How can I access this object from other methods within the class?