Search code examples
swiftxcodesqlite.swift

How can I declare a variable nil until I need it?


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)
    }
}

Solution

  • I could call connect at the init, but I don't want to call Connect until I need it.

    Absolutely right! Don't do anything like that in init.

    Just rewrite your declaration to make the Connection nil, precisely as you suggested:

    class MySQL {
        var db : Connection? = nil
        var dbPath : String
        
        init() {
            dbPath = getDocumentsDirectory().absoluteString + "db.sqlite3"
        }
        
        func open(){
            do{
                db = try Connection(dbPath)}
            catch{}
    
            let users = Table("users")
            print(users)
        }
    }
    

    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 is nil. You can use Optional chaining to do that painlessly. You could avoid that by declaring db as Connection! instead of Connection? but that risks a later crash and I can't recommend it.