iosswiftsqliteswift2fmdb

Insert a potentially null value into the sqlite database in iOS


I have a class called Content, whose URL property is nullable (URL: String?). I'd like to store this URL property in my sqlite database using FMDB, but Xcode complains I need to unwrap the optional with !

but the problem is when I do content.URL! it crashes because it's nil.

 success = db.executeUpdate("INSERT INTO CONTENT(ID, Icon, Title, Description, URL, IsActive) VALUES(?,?,?,?,?,?,?,?,?)", withArgumentsInArray: [content.ID, content.icon, content.title, content.description, content.URL!, content.isActive])

How can I successfully insert URL both when it has and does not have a value?

Thanks!


Solution

  • One approach that I use for cases like this is to create a class extension.

    For example:

     class func databaseSafeObject(object: AnyObject?) -> AnyObject {
        if let safeObject: AnyObject = object{
            return safeObject;
        }
    
        return NSNull();
    }
    

    Then you can just use:

    NSObject.databaseSafeObject(content.URL);
    

    to get something that can be directly inserted in the db.