[swift-evolution] [Idea] Deferable type for swift and smaller defer scope

Kwanghoon Choi eyerama at gmail.com
Wed Jul 6 21:40:50 CDT 2016


I have been using defer for very happy. It’ like with keyword on python,
using easily for needs closing context like NSFileHandle.

anyway defer is very useful statement for function scope.

However, I thinking now, What if i can use more small defer.

below, that’s codes of idea.

// firstbly, create Deferable protocol for decorating.
protocol Deferable {
    func finish()
}

// secondly, extension NSFileHandle for deferable
extension NSFileHandle: Deferable {}

extension Deferable {
    func finish() {
        switch self {
        case let fh as NSFileHandle:
            fh.closeFile()
        default:
            break
        }
    }
}

// i have no skill create keyword for swift. so i make custom operator
infix operator !! {}
func !! <D: Deferable>(lhs: D, rhs:(target: D)->Void) -> D{
    defer {
        lhs.finish()
        print("finished")
    }
    rhs(target: lhs)
    return lhs
}


// for testing
class Test {
    func test() {
        NSFileHandle(forReadingAtPath: path)! !! {
            print("read \($0.readDataOfLength(10))")
        }
    }
}

Test().test()

->
*read <blah blah...>*
*finished*

*i have no idea this is how to useful.*
*but it is make me more funny programming on swift.*

*thankyou *
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160707/d1879334/attachment.html>


More information about the swift-evolution mailing list