NullHypothesis
NullHypothesis

Reputation: 4506

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!

Upvotes: 0

Views: 2755

Answers (4)

Ronk
Ronk

Reputation: 373

The AnyObject type didn't work for me when working with variables of type Int and Double, so I created a similar function to handle optional Swift variables.

private func getOptionalOrNull(_ possibleValue:Any?)->Any {
  if let theValue = possibleValue {
    return theValue
  } else {
    return NSNull()
  }
} 

Upvotes: 0

Gwendal Roué
Gwendal Roué

Reputation: 4044

There exists Swift wrappers for SQLite that may be a better fit that fmdb which can run in Swift but does not use Swift features such as optionals (that you miss here), type safety, and error handling. See for example my GRDB.swift http://github.com/groue/GRDB.swift which was heavily influenced by ccgus/fmdb.

Upvotes: 0

john_ryan
john_ryan

Reputation: 1787

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.

Upvotes: 2

NullHypothesis
NullHypothesis

Reputation: 4506

So this ended up working for me, although it seems kinda irking that this is how it has to be:

(content.URL == nil ? NSNull() : content.URL!)

Upvotes: 0

Related Questions