Reputation: 1469
I have three functions, each dependent on the previous.
let dbPath = createDBPath()
let db = openDatabase(dbPath!)
readQuestionsFromDB(db!)
The first line creates the database path ( if not gives a fatal error, as there is no point in continuing execution if I don't have access to the file stucture ). The second line opens the database using the path (the unwrap is ok here, as if we don't have a path we'll have crashed by this point in any case). The third line reads quiz questions from the database that needs to be opened, if the database has an issue it will also crash from within the function as if we can't read a DB there is something seriously wrong.
What is the best way to structure this? An if - let pyramid? I've split this into three functions to try to separate out functionality for readability. Perhaps I should pass the db and db path as class properties? I'm not sure...
Upvotes: 1
Views: 55
Reputation: 271040
I don't see anything wrong with your current code, but if you really want to change the aesthetics of your code, you can call map
on the optionals.
createDBPath().map(openDatabase).map(readQuestionsFromDB)
Upvotes: 0
Reputation: 1378
I’d do this
if let dbPath = createDBPath(),
let db = openDatabase(dbPath) {
readQuestionsFromDB(db)
}
Upvotes: 2