0

i just started learning Swift4. I have read all the suggestions for stack overflow duplicate questions, but I could not solve or understand my problem.

I am fetching Data from a SQLite.swift database:

ViewController.swift:

import Foundation
import SQLite

// Load DB with SQLite.swift
let path = Bundle.main.path(forResource: "myDataBaseFile", ofType: "sqlite")!
let db = try! Connection(path, readonly: true)

// SQLite.swift define table
let table = Table("table")

// SQLite.swift define columns 
let id = Expression<Int>("id")
let medium = Expression<String>("medium")

// Function to get query result
func queryForMedium(idForQuery: Int) -> String? {
    let media = try? db.scalar(table.select(medium).filter(id == idForQuery))
    return media
}

// ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // Value for ID = 2 access a SQL Null value
    anOptionalString = queryForMedium(idForQuery: 2)

    if anOptionalString != nil {
        print("Contains a value!")
    } else {
        print("Doesn’t contain a value.")
    }

}

Result:

  • ID = 1 contains "Test" -> App runs: Console Output:
    Contains a value!
  • ID = 2 contains NULL -> CRASH: Console Output:
    SQLite was compiled with optimization - stepping may behave oddly; variables may not be available.

Xcode Screenshot after App Crash

Note: I have tried to disable Optimazion Level (Build Settings), the result is the same.

I would be grateful for help or solutions!

1 Answer 1

1

You need to tell SQLite.swift that the medium column can be null by using an optional generic, <String?>

Change

let medium = Expression<String>("medium")

to

let medium = Expression<String?>("medium")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.