[swift-evolution] Cancelable named defer statements

Jay Abbott jay at abbott.me.uk
Sat Jan 7 14:45:16 CST 2017


A closure assigned to a variable is already a named handler…
Make it optional and it’s now a cancelable named handler…
Put it in a defer block and you have exactly what you want, a cancelable
named defer handler…

func doSomething(input: String) -> String? {

    // Create a cancelable named defer handler
    var namedDeferHandler: (() -> Void)? = { print("It didn't work,
but I've taken care of any cleaning up.") }
    defer { namedDeferHandler?() }

    // Check the input
    if input == "" { return nil }

    // Cancel the named defer handler
    namedDeferHandler = nil

    return "It worked!"
}

It’s very flexible, you can have multiple handlers and cancel only some of
them, include some non-optional code in the defer block itself, etc.
​

On Sat, 7 Jan 2017 at 18:45 Charles Srstka via swift-evolution <
swift-evolution at swift.org> wrote:

> > On Jan 7, 2017, at 12:40 PM, D. Felipe Torres via swift-evolution <
> swift-evolution at swift.org> wrote:
> >
> > Any cancelable defer addition we could come up with will need a
> flag/state to indicate so, which won't be that much different from what you
> wrote.
> >
> > Having said that, for your example may I suggest this approach instead:
> >
> > func openFile(kind: String) -> UnsafeMutablePointer<FILE>? {
> >
> >     var file = fopen("MyFile.txt", "r")
> >     guard  fileIsValid(file)
> >         && fileContainsData(file, kind)
> >         && !fileDataOutOfDate(file) else {
> >         fclose(file)
> >     }
> >
> >     return file
> > }
>
> Or:
>
> func openFile(kind: String) -> UnsafeMutablePointer<FILE>? {
>     var file = fopen("MyFile.txt", "r”)
>
>     do {
>         if fileIsNotValid(file) { throw MyError.fileIsNotValid }
>
>         if fileDoesNotContainsData(file, kind) { throw
> MyError.doesNotContainData }
>
>         if fileDataOutOfDate(file) { throw MyError.dataOutOfDate }
>
>         return file
>     } catch {
>         fclose(file)
>     }
> }
>
> Charles
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170107/f398d2a5/attachment.html>


More information about the swift-evolution mailing list