A simple app that demonstrates the usage of SQLite within Swift.
- Installation
- SQLite Considerations
- Implementation in Swift
- Notable Classes
- References
- Install pods with
pod install
- Build in
Xcode 11.0
or newer, withSwift 5
.
A Cocoa / Objective-C wrapper around SQLite
A tool to enforce Swift style and conventions.
- SQLite is not thread-safe, thus you must treat all connections within one thread.
- Each database connection must always be closed when completed.
- SQLite is a relational database.
libsqlite3.tbd
is a library included on all iOS/macOS devices, thus it does not increase the binary size of your application- As an older technology, the main interface is C.
To use SQLite in Swift, we must be using C-code in Swift.
This gives us three options.
-
- Import
SQLite3
and use it directly in Swift, working with the C-style naming convention.
- Import
-
- Use Objective-C as an intermediary for C-level SQLite, which we can then interface with, using Swift.
-
- Use an existing framework that does 2. because it is a solved problem.
We will be using approach 3, with fmdb.
fmdb also addresses some of the other issues with SQLite databases (none of which are addressed here).
The primary class we will be interacting with is SQLiteManager
.
Of notability, the following CRUD functions are implemented:
- created automatically when an instance of
SQLiteManager
is instantiated, if the table does not already exist
SQLiteManager+Create.swift
- can press the
+
button at the top-right to calladdItemButtonAction
inDatesListController
- sets the current date and sets a random hexidecimal value for the name
- saves the entry within SQLite
SQLiteManager+Read.swift
- on app start, all entries are loaded into the table in
DatesListController
- each create/update/delete also reloads all entries, for the sake of demonstration
SQLiteManager+Update.swift
- tapping on any entry on the table assigns a new hexidecimal value
- SQLite value is updated, then all entries are refreshed from the backing store
SQLiteManager+Delete.swift
- swipe-left action on any entry allows for easy deletion
- implemented in respective UITableViewDelegate method
trailingSwipeActionsConfigurationForRowAt
oreditActionsForRowAt
, depending on OS version