Search code examples
swiftfmdb

How to handle NULL in FMDB + Swift 3


i'm using fmdb and some of my rows are NULL

enter image description here

and in my code :

let name = try database.executeQuery("select name from tb_item", values: nil)
        let description = try database.executeQuery("select summary_statement from tb_item", values: nil)
        let imageTry = try database.executeQuery("select main_image from tb_item", values: nil)
        while name.next() && description.next() && imageTry.next() {
            let title = name.string(forColumn: "name")
            let description = description.string(forColumn: "summary_statement")
            let imageTry = imageTry.string(forColumn: "main_image")
                let list2 = modelData()
                list2.title = title!
                list2.description = description!
                list2.image = imageTry! //fatal error: unexpectedly found nil while unwrapping an Optional value
                list.append(list2)
        }

How to handle NULL so it doesn't error?


Solution

  • Create an imageset and name it something say "blank", and don't assign any image to it. And simply use that like below:

    list2.image = imageTry ?? UIImage(named: "blank")
    

    This means if imageTry is nil then it will assign blank image to it.