<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><br class=""><div><blockquote type="cite" class=""><div class="">On 4 May 2016, at 00:46, Aleksandar Petrovic via swift-evolution <<a href="mailto:swift-evolution@swift.org" class="">swift-evolution@swift.org</a>> wrote:</div><br class="Apple-interchange-newline"><div class=""><div class="">Hi swift-evolution,<br class=""><br class="">I want to apologize in advance for my clumsy English. It's (obviously) not my first language.<br class=""><br class="">Recent discussion about property behaviours reminded me of function decorators in Python. I think decorators can nicely fit in Swift, too.<br class=""><br class="">First, a bit of explanation for the uninitiated. Decorator is a function that transform other function - it receives some function and returns a function of the same signature. Lets make some dead simple decorator:<br class=""><br class="">typealias Decorated = (Double, Double) -> Double<br class=""><br class="">func hiDecorator(fn: Decorated) -> Decorated {<br class=""> return { x, y in<br class=""> print("Hi from decorator!")<br class=""> return fn(x, y)<br class=""> }<br class="">} <br class=""><br class="">func multiply(a: Double, _ b: Double) -> Double {<br class=""> return a * b<br class="">}<br class=""><br class="">let decoratedMultiply = hiDecorator(multiply)<br class="">print("Result: \(decoratedMultiply(2, 3))") <br class=""><br class=""><br class="">The above code should print:<br class="">Hi from decorator!<br class="">Result: 6<br class=""><br class="">We can use decorators with the current Swift, but they're a bit cumbersome - either we need to store decorated function and remember to use it instead of the original one, or remember to do the decoration on every call.<br class=""><br class="">Instead, we can write something like this:<br class=""><br class="">[hiDecorator]<br class="">func multiply(a: Double, _ b: Double) -> Double {<br class=""> return a * b<br class="">}<br class=""><br class="">... and that code should be transformed into following during compilation:<br class=""><br class="">func multiply(a: Double, _ b: Double) -> Double {<br class=""> let fn: (Double, Double) -> Double { _a, _b in<br class=""> return _a * _b<br class=""> }<br class=""> <br class=""> let decorated = hiDecorator(fn) <br class=""> return decorated(a, b)<br class="">}<br class=""><br class="">Outside, the function looks like before, so the change is compatible with virtual or interface extension functions.<br class=""><br class="">Sometimes we'll need to pass some additional data to the decorator. That's fine, as long as the last argument is the target function:<br class=""><br class="">func logUsage<I, O>(fnName: String, fn: (I) -> O) -> ((I) -> O) {<br class=""> return { _i in<br class=""> print("Function \(fnName) enter")<br class=""> defer { print("Function \(fnName) exit") }<br class=""> return fn(_i)<br class=""> }<br class="">}<br class=""><br class="">Let's use it:<br class=""><br class="">[logUsage("increment")]<br class="">func increment(a: Int) -> Int { return a + 1 }<br class=""><br class="">[logUsage("justPrint")]<br class="">func justPrint(s: String) { print(s) }<br class=""><br class="">In the above code, the compiler should generate internal decorator call by combining provided parameter and decorated function.<br class=""><br class=""><br class="">Why decorators?<br class=""><br class="">It's important to say that proposed decorators change are pure syntactic sugar. Everything we can do with this change can be accomplished with the current Swift language. But, it gives to programmer a tool to express intentions more clearly and move repeating code away. <br class=""><br class="">Sometimes decorators are just a convenient way to quickly add code. In the example above, logging is added with just one line of code and can be easily removed - the function body is not changed. <br class=""><br class="">Sometimes decorators can be used as a poor man dependency injection mechanism, so we can write functions like this:<br class=""><br class="">// if conn is nil, dbInit decorator will provide (global) one, and properly close it after doSomeDbWork exits<br class="">[dbInit]<br class="">func doSomeDbWork(conn: DbConnection? = nil) { ... } <br class=""><br class=""><br class="">We can use decorators in the standard library to, in a way, extend language:<br class=""><br class="">[asyncMain]<br class="">func doSomething() { ... } // this function will be posted to main queue<br class=""><br class="">[synchronized]<br class="">func foo() { ... } // synchronized decorator uses either objc_sync_enter/exit or post on some queue to ensure mutual exclusion<br class=""><br class="">Or to do some more exotic operations:<br class=""><br class="">[repeatUntilDone(maxAttempt: 5)]<br class="">func connectToServer(url: String) -> Bool { ... }<br class=""><br class="">Abstract functions are frowned upon in Swift community, but if we can't live without it, we can signal our intent more clearly with decorator:<br class=""><br class="">class T {<br class=""> [abstract] func bar() {} // abstract decorator will assert on call<br class="">}<br class=""><br class="">Etc, etc. Sounds interesting?<br class=""><br class="">Alex <span class="Apple-tab-span" style="white-space:pre">        </span><span class="Apple-tab-span" style="white-space:pre">        </span> <span class="Apple-tab-span" style="white-space:pre">        </span> <span class="Apple-tab-span" style="white-space:pre">        </span><span class="Apple-tab-span" style="white-space:pre">        </span> <br class="">_______________________________________________<br class="">swift-evolution mailing list<br class=""><a href="mailto:swift-evolution@swift.org" class="">swift-evolution@swift.org</a><br class="">https://lists.swift.org/mailman/listinfo/swift-evolution<br class=""></div></div></blockquote></div><br class=""><div class=""><br class=""></div><div class="">Given that we might be doing "property behaviours” (<a href="https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md" class="">https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md</a>), which are basically property decorators, it probably makes sense to look at how that could work for function decorators.</div><div class=""><br class=""></div><div class="">After all, you could create a property behaviour around a closure and use that as a kind of function decorator. It would just be messy.</div><div class=""><br class=""></div><div class="">Karl</div></body></html>