Let's say you have a method which performs some networking actions, which can obviously fail, but in different ways:
func performNetworkStuff() {
fetchSomething(then: { condition in
if condition {
}
// failure due to condition
else {
failureAction1()
failureAction2()
variable1 = value
etc...
}
}) {
// failure due to network
failureAction1()
failureAction2()
variable1 = value
etc...
}
}
But instead, we could DRY it up a little bit, by storing the failure actions into a block beforehand:
func performNetworkStuff() {
let handleFailure = {
failureAction1()
failureAction2()
variable1 = value
etc...
}
fetchSomething(then: { condition in
// success
if condition {
}
// failure due to condition
else {
handleFailure()
}
}) {
// failure due to network
handleFailure()
}
}
This way you can be sure the same code is properly run on all failures, and if something needs to be changed, it has to be changed in only one place.