奇怪的致命错误:在展开Optional值时意外发现nil

时间:2017-08-18 08:34:38

标签: ios swift sqlite optional

我在我的iOS Swift应用程序中使用sqlite。当我从数据库中选择一行时,下面是一个错误代码段。

问题是:它有一个值,但会产生致命错误。 (在展开Optional值时意外发现nil)

enter image description here

我使用的库是:stephencelis/SQLite.swift

import Foundation
import SQLite

struct studentDB {
    let table = Table("students")
    let code = Expression<String>("code")
    let name = Expression<String>("name")
    let gender = Expression<Int>("gender")
    let birth = Expression<String>("birth")
    let born = Expression<String>("born")
    let className = Expression<String>("class")
    let speciality = Expression<String>("speciality")
    let department = Expression<String>("department")
    let faculty = Expression<String>("faculty")
    let training = Expression<String>("training")
    let course = Expression<String>("course")
    let advisor = Expression<String>("advisor")
}

struct student {
    let code: String!
    let name: String?
    let gender: Int?
    let birth: String?
    let born: String?
    let className: String?
    let speciality: String?
    let department: String?
    let faculty: String?
    let training: String?
    let course: String?
    let advisor: String?
}

class Student {
    class func getStudent(code: String) -> student? {
        let studentDBInfo = studentDB()
        let studentRaw = try! userDatabase.pluck(studentDBInfo.table.filter(studentDBInfo.code == code))
        if (studentRaw != nil) {
            let studentInfo = student(
                code: studentRaw![studentDBInfo.code],
                name: studentRaw![studentDBInfo.name],
                gender: studentRaw![studentDBInfo.gender],
                birth: studentRaw![studentDBInfo.birth],
                born: studentRaw![studentDBInfo.born],
                className: studentRaw![studentDBInfo.className],
                speciality: studentRaw![studentDBInfo.speciality],
                department: studentRaw![studentDBInfo.department],
                faculty: studentRaw![studentDBInfo.faculty],
                training: studentRaw![studentDBInfo.training],
                course: studentRaw![studentDBInfo.course],
                advisor: studentRaw![studentDBInfo.advisor]
            )
            return studentInfo
        } else {
            return nil
        }
    }
}

所有其他专栏工作正常。 更清楚:

print(studentRaw![studentDBInfo.code]) -> crash 
print(studentRaw![studentDBInfo.name]) -> "Pham Tuan Anh"

1 个答案:

答案 0 :(得分:1)

你是强行打开studentRaw,然后崩溃,因为它是零。在尝试使用它之前,您需要添加以下内容。

guard let studentRaw = studentRaw else {
    // Handle the error
    return
}

至于为什么code有一个值,看起来你正在重用那个变量,所以可能以前已经设置过。