1
votes

I wonder how I would use a default value for a boolean in SQLite in swift. I am using the following library: https://github.com/stephencelis/SQLite.swift I have a query that won't be executed if I don't use all values.

I am doing this in a loop:

let insert = table.insert(name <- names[i])

Catches error:

NOT NULL constraint failed: table.bool (code: 19)

My problem here is that I want the bool value to be a default of NULL.

I tried to create my database with a default value like this:

let bool = Expression<Bool?>("bool") 

So what can I do to create default values in SQLite in swift?

1

1 Answers

0
votes

The error clearly tells you that you can't have null in this column so setting null as default is pointless. So your first step is to change the database definition to allow null (if it's possible).

A better option might be to reconsider why you want to have null for a boolean value or if the type of the column should be something different.

In regard to default values I would solve this in swift by moving the insert into a separate function and use swift support for default values for parameters.

Example

func insertStuff(withName name: String, flag: Bool = false) {
   //db-code
}

and then call it with/without all parameters

insertStuff(withName: "abc", flag: true)
insertStuff(withName: "edf")

Update
If you do want the column to be nil you can use an optional parameter

func insertStuff(withName name: String, flag: Bool? = nil) {
   //db-code
}