我刚刚开始学习Swift4。我已经阅读了有关堆栈溢出重复问题的所有建议,但无法解决或理解我的问题。
我正在从SQLite.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.")
}
}
Contains a value!
SQLite was compiled with optimization - stepping may behave oddly; variables may not be available.
注意: 我尝试禁用Optimazion Level(构建设置),结果相同。
感谢您的帮助或解决方案!
答案 0 :(得分:1)
您需要通过使用可选的泛型medium
告诉SQLite.swift <String?>
列可以为空
更改
let medium = Expression<String>("medium")
到
let medium = Expression<String?>("medium")