stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.68k stars 1.56k forks source link

unexpectedly found nil while unwrapping an Optional value #922

Closed RockyQu closed 3 years ago

RockyQu commented 5 years ago

There is a table here

do {
            try db.run(TABLE_DEVICE.create(ifNotExists: true) { table in
                table.column(TABLE_DEVICE_ID, primaryKey: .autoincrement)
                table.column(TABLE_DEVICE_MAC)
                table.column(TABLE_DEVICE_ARTS)
                table.column(TABLE_DEVICE_COEFFICIENT)
                table.column(TABLE_DEVICE_LANGUAGES)
                table.column(TABLE_DEVICE_AREA)
                table.column(TABLE_DEVICE_UUID)
            })

            Logg(item: "create table device success.")
        } catch {
            Logg(item: "create table device failure:\(error).")
 }

Below is a query method

func getDeviceByUUID(uuid: String) -> DeviceEntity {
        let device = DeviceEntity()
        for item in try! db.prepare(TABLE_DEVICE.filter(TABLE_DEVICE_UUID == uuid)) {
            device.id = item[TABLE_DEVICE_ID]
            device.arts = item[TABLE_DEVICE_ARTS]
            device.coefficient = item[TABLE_DEVICE_COEFFICIENT]
            device.languages = item[TABLE_DEVICE_LANGUAGES]
            device.area = item[TABLE_DEVICE_AREA]
            device.uuid = item[TABLE_DEVICE_UUID]
            break
        }

        return device
}

In the following line of code, an error is reported.

device.area = item[TABLE_DEVICE_AREA]

The area field in the table may be null. How can I tell if this value is empty when querying? I use the following judgment but it does not work.

 if item[TABLE_DEVICE_ARTS] != nil {
     device.area = item[TABLE_DEVICE_AREA]
}
nathanfallet commented 3 years ago

Use Expression<Type?> instead of Expression<Type>.