I am currently building an app in swift that uses FMDB to interact with a database that is stored on the device. I chose to use FMDB since I have experience using it with Objective C, and it says it supports swift.
I am having problems with returning booleans in swift when executing a statement. Here is an image of the update functions available to me when using FMDB in an Objective C class, notice how the overwhelming majority return bools
And here are the funcs available in swift:
Doesn't give me much to work with!
Here is an existing query I am currently using in an app (with names changed).
sql = @"INSERT INTO Table (IdValue, AnotherIDValue) VALUES (?, ?);";
BOOL success = [db executeUpdate:sql,
[NSNumber numberWithLong:preference.idvalue1],
[NSNumber numberWithLong:preference.idvalue2],
nil];
Once this statement runs I close off the database & return the boolean. This essentially gives me a completion block and lets me hold the UI up until the sql has successfully completed.
Unfortunately with swift I have alot less to work with, and I don't really understand the function inputs that return bools. So far in my swift database class I run updates like so:
try! db.executeUpdate(sqlStatement, values: dataArray)
Giving me safety, if it fails, but no way to return a success boolean. I am wondering if anyone has any suggestions for implementing the database class like I showed in objective c.
The only alternative I can see is rewriting the class in objective c, however I would prefer to keep this app 100% swift.
From Adopting Cocoa Design Patterns in the "Using Swift with Cocoa and Objective-C" reference:
Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift’s native error handling functionality.
Therefore the Objective-C method
- (BOOL)executeUpdate:(NSString *)sql values:(NSArray *_Nullable)values error:(NSError *_Nullable __autoreleasing *)error
is mapped as
func executeUpdate(sql: String, values: [Any]?) throws
into Swift, and must be called with (a variant of) try
.
If you are only interested in the success/failure status, but not
in the actual error message (as in your Objective code), then
you can use try?
, which evaluates to nil
if the evaluation failed:
let success = (try? db.executeUpdate(sqlStatement, values: dataArray)) != nil