上一篇很高興已經使用SQLite.swift來儲存
但回傳的數值竟然報錯
經過多次的測試
以及重裝APP發現
回傳數值並不是我存入的類型
而是返回Binding?類型
這類型我竟然沒辦法使用as 來變換型態
也不能使用Int(變數)來改變
那今天我就來debug這個問題吧
目前進度將原先
寫死的SQLite.swift 語法
改為活得 SQL語法帶入
可以直接使用dic的key下去儲存在model
func reloadDataOlder(tableName:String) {
productList = [ProductItemtMode]()
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let db = try? Connection("\(path)/Chuhuo.sqlite")
users = Table(tableName)
for user in (try? db?.prepare(users))!! {
let currentDate = user[date]
let dataFormatter = DateFormatter()
dataFormatter.locale = Locale(identifier: "zh_Hant_TW")
dataFormatter.dateFormat = "YYYY年MM月dd日"
let stringDate = dataFormatter.string(from: currentDate)
print(stringDate)
let productItemMode = ProductItemtMode()
productItemMode.price = user[price]
productItemMode.product = user[product]
productItemMode.date = user[date]
productItemMode.amount = user[amount]
productList.append(productItemMode)
}
}
func reloadData(selectCode:String){
productList = [ProductItemtMode]()
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let db = try? Connection("\(path)/Chuhuo.sqlite")
//"SELECT SUM(price), product, date, amount FROM stock GROUP BY product"
for user in (try? db?.prepare(selectCode))!! {
let productItemMode = ProductItemtMode()
productItemMode.price = user[0] as? Int
productItemMode.product = user[1] as? Int
productItemMode.date = user[2] as? Date
productItemMode.amount = user[3] as? Int
productList.append(productItemMode)
print(productList[0].price)
}
}
照理說應該可以啊 直接as? Int
就可以轉換成Int
但我錯了直接報錯
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Binding Optional沒辦法直接轉換
這裡我找很久 很多中文網站沒有介紹
或是我沒查到
但我在國外網站有找到類似問題
就是SQLite.swift value轉換問題
連結
http://www.devjockeys.com/blog/swift-ios/swift-convert-an-optional-binding-value-to-an-integer-sqlite/
這邊我直接貼程式碼
大概要這樣寫
func reloadData(selectCode:String){
productList = [ProductItemtMode]()
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let db = try? Connection("\(path)/Chuhuo.sqlite")
//"SELECT SUM(price), product, date, amount FROM stock GROUP BY product"
for user in (try? db?.prepare(selectCode))!! {
let optionalCount : Int64 = Optional(user[0]) as! Int64
let lCount = Int(optionalCount)
}
}
重點是這段
let optionalCount : Int64 = Optional(user[0]) as! Int64
let lCount = Int(optionalCount)
要先轉換成Int64再轉Int !?
認真嗎 目前我找到此種方法解
之後有機會 我要再找找最佳解
結束