Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
func retrieveArticles(searchText: String) {
precondition(db != nil, "Database not open")
let query = "SELECT * FROM articles WHERE title = ? "
var statement: OpaquePointer?
guard sqlite3_prepare(db, query, -1, &statement, nil) == SQLITE_OK else {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing Select: \(errmsg)")
defer { sqlite3_finalize(statement) }
guard sqlite3_bind_text(statement, 1, searchText, -1, nil) == SQLITE_OK else {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding title: \(errmsg)")
while sqlite3_step(statement) == SQLITE_ROW {
let id = sqlite3_column_int(statement, 0)
let author = sqlite3_column_text(statement, 1)
let title = sqlite3_column_int(statement, 2) // is title really an integer?
if let author = author {
articles.append(Article(id: Int(id), author: String(cString: author), title: "\(title)"))
} else {
print("Author is required")

This comment has been minimized.

Copy link
Owner Author

robertmryan commented Aug 31, 2019

A few observations:

  1. You should defer the sqlite3_finalize so that it's called, regardless of how you exit this routine.
  2. Method names should start with lowercase letters.
  3. For those errors that are hard stops, I'd suggest guard, in which the compiler verifies that you have returned.
  4. When retrieving the author name, you need to decide what you want to do if the name is missing in the table. But using String(describing:) is not what you want.
  5. I'd advise against using * is SQL SELECT statements because one's code should not be dependent upon the sequence of columns in the table. It's probably prudent to explicitly list the column names.
  6. It makes no sense to make the search string an optional (or, if you did, you'd need to handle it correctly ... the original code sample won’t do what you intended).
  7. I’d suggest changes to variable names (I’d suggest statement instead of stmt3; the ArticleList should also start with lowercase letter, and I’d personally just call it articles; etc.).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.