How do I use SQLite directly from Swift?

Using SQLite directly from Swift is a straightforward process that allows developers to manage local databases seamlessly within their applications. SQLite is an embedded database engine that is light and easy to integrate. Below is an example of how to set up and use SQLite in a Swift application.

import SQLite3 class Database { var db: OpaquePointer? init?() { // Open database if sqlite3_open("myDatabase.sqlite", &db) != SQLITE_OK { print("Error opening database") return nil } createTable() } func createTable() { let createTableString = "CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT);" var createTableStatement: OpaquePointer? = nil if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK { if sqlite3_step(createTableStatement) == SQLITE_DONE { print("Contacts table created.") } else { print("Contacts table could not be created.") } } sqlite3_finalize(createTableStatement) } deinit { sqlite3_close(db) } } let database = Database()

SQLite Swift Database iOS Development Local Storage