Swift:从 SQLite.swift 访问 NULL 值时应用崩溃

Swift: App crashes when accessing NULL value from SQLite.swift

我刚开始学习 Swift4。我已经阅读了所有关于堆栈溢出重复问题的建议,但我无法解决或理解我的问题。

我正在从 SQLite.swift 数据库中获取数据:

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.")
    }

}

结果:

注意: 我试过禁用优化级别(构建设置),结果是一样的。

如有帮助或解决方案,我将不胜感激!

您需要使用可选泛型 <String?>

告诉 SQLite.swift medium 列可以为空

改变

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

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