MK DEV MK DEV - 5 months ago 33
Swift Question

Error in Singleton usng SQLite Swift

When I am trying to fetch all the data in the SQLite Database in swift using singleton, I get an error in sharedInstance and zero results are fetched.

Here is my code:


import SQLite

class DatabaseManager {

let shareInstance = DatabaseManager()
let recipeTable = Table("recipes")
let id = Expression<String>("id")
let title = Expression<String>("title")
let category = Expression<String>("category")
let recipe = Expression<String>("recipe")
let bookmark = Expression<String>("Bookmark")

let db: Connection = {
let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return try! Connection("\(path)/recipe.sqlite")

func findAll() -> Array<foodRecipe>{
var foodRecipeArray = [foodRecipe]()

//for row in try db.prepare(,title,recipe,category,bookmark).filter(category == "appetizers")){
for row in try shareInstance.db.prepare(recipeTable){
let fd = foodRecipe() = row[id]
fd.title = row[title]
fd.recipe = row[recipe]
fd.category = row[category]
fd.bookmark = row[bookmark]

catch let error as NSError {
print("Error: \(error.description)")
return foodRecipeArray


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

var foodRecipeArray: [foodRecipe]

let dbMngr: DatabaseManager = DatabaseManager()

foodRecipeArray = dbMngr.findAll()

print("Food Recipe Array Count: \(foodRecipeArray.count)") //return 0

print("Food Recipe Array: \(foodRecipeArray)") //result nil

// Override point for customization after application launch.
return true



A shared instance used as singleton must be static

static let shareInstance = DatabaseManager()