在解包一个Optional值时意外地发现了nil:Swift - FMDB - executeQuery

时间:2016-01-08 22:04:47

标签: swift sqlite fmdb

我是Swift,FMDB和一般开发的新手,我和我在运行时遇到致命错误:unexpectedly found nil while unwrapping an Optional Value.错误发生在executeQuery

初步尝试和相关代码:

        var rightAnswer:FMResultSet?
        var memberDatabase:FMDatabase?
    ....
override func viewDidLoad() {
let path = NSBundle.mainBundle().pathForResource("1_celebs", ofType: "sqlite3")
        memberDatabase = FMDatabase(path: path)
        if memberDatabase!.open(){
            print("database is ready")//it works if I comment out the stuff in loadquestion() 
        }
        else{
            print("error finding database")
        }
...
    func loadQuestion(){
        let querySQL = "SELECT Quote, Answer, answerNumber, Celeb1, Celeb2, Celeb3, img1, img2, img3, feedbackImg, Context FROM celebs WHERE answeredRight = 'no' ORDER BY RANDOM() LIMIT 1"

        rightAnswer = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
        rightAnswer!.next()

然后我在func loadQuestion()

中尝试了这个
let results:FMResultSet? = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: nil)
        while(results?.next() == true)
        {...}

然后我尝试了这个:

do{
   rightAnswer = try memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
   while rightAnswer!.next(){...}
 } catch let error as NSError {
    print("failed: \(error.localizedDescription)")
 }

然后,这个:

   do{
   let rs = try memberDatabase!.executeQuery(querySQL, values: nil)
    while rs.next(){...}
} catch let error as NSError {
  print("failed: \(error.localizedDescription)")
}

我每次在executeQuery行都会收到相同的错误!如果我试图摆脱感叹号和问号,那么我在控制台上收到错误,说无法打开数据库。

1 个答案:

答案 0 :(得分:2)

问题在于memberDatabasenil

您应该确保填充该变量。

另一个建议是,你应该避免强行解包操作员。它绕过编译器检查nil(或可能的nil)值。

Swift确实提供了更好的解决方案,比如

条件展开

if let memberDatabase = memberDatabase {
    try memberDatabase.executeQuery(querySQL, values: nil)
}

保护

guard let memberDatabase = memberDatabase else { return }
try memberDatabase.executeQuery(querySQL, values: nil)