Reputation: 12215
I have this piece of code, but I would like to improve it a bit by making it more "functional"
var person = Person.getOne(on: db, with: ["name": name])
if person == nil {
let personId = try Person.insert(on: db, with: ["name": name])
person = Person.getOne(on: db, withIdentifier: personId)
}
So I did :
let harbor = Harbor.getOne(on: db, with: ["name": formattedName]) ?? {
let harborId = try Harbor.insert(on: db, with: ["name": formattedName])
return Harbor.getOne(on: db, withIdentifier: harborId)
}()
It would work perfectly without try
ing to insert. So I have to mark my anonymous closure to throws
and try
to execute it.
Is it possible do achieve this in swift?
Upvotes: 1
Views: 537
Reputation: 12215
Thanks to @hamish, the solution was to add a try
before the entire expression:
let harbor = try Harbor.getOne(on: db, with: ["name": formattedName]) ?? {
let harborId = try Harbor.insert(on: db, with: ["name": formattedName])
return Harbor.getOne(on: db, withIdentifier: harborId)
}()
It seems strange because the first getOne
do not throws
any error.
Upvotes: 1