[swift-evolution] Cancelable named defer statements

Charles Srstka cocoadev at charlessoft.com
Sat Jan 7 12:45:18 CST 2017


> 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


More information about the swift-evolution mailing list