Martin
Martin

Reputation: 12215

throwable anonymous closure in swift

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 trying 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

Answers (1)

Martin
Martin

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

Related Questions