[swift-evolution] Cancelable named defer statements

D. Felipe Torres warorface at gmail.com
Sat Jan 7 12:40:20 CST 2017


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

}

On Sat, Jan 7, 2017 at 7:20 PM, Rien via swift-evolution <
swift-evolution at swift.org> wrote:

> Is there any interest in a proposal to introduce a named defer statement
> that can be cancelled?
>
> Lately I find myself writing this kind of code:
>
> func openFile(kind: String) -> UnsafeMutablePointer<FILE>? {
>
>
>     var file = fopen("MyFile.txt", "r")
>
>
>     var closeFile = true
>
>     defer { if closeFile { fclose(file) } }
>
>
>     if fileIsNotValid(file) { return nil }
>
>     if fileDoesNotContainsData(file, kind) { return nil }
>
>
>     if fileDataOutOfDate(file) { return nil }
>
>
>     // Prevent the deferred handler from closing the file
>     closeFile = false
>
>     return file
> }
>
> Which imo would be much cleaner if we were able to write:
>
> func openFile(kind: String) -> UnsafeMutablePointer<FILE>? {
>
>     var file = fopen("MyFile.txt", "r")
>
>     CLOSE_FILE: defer { fclose(file) }
>
>     if fileIsNotValid(file) { return nil }
>
>     if fileDoesNotContainsData(file, kind) { return nil }
>
>     if fileDataOutOfDate(file) { return nil }
>
>     // Prevent the deferred handler from closing the file
>     cancel CLOSE_FILE
>
>     return file
> }
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Swiftrien
> Project: http://swiftfire.nl
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>


-- 
++++++++++++++++++++++++++
Diego Torres.
Phone (Mobile Germany): +49 157 30070985
Phone (Landline Chile): +56 2 29790978
Web: dtorres.me
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170107/87006a70/attachment.html>


More information about the swift-evolution mailing list