{"id":6968,"date":"2014-06-17T19:32:11","date_gmt":"2014-06-17T16:32:11","guid":{"rendered":"http:\/\/railsware.com\/blog\/?p=6968"},"modified":"2021-08-23T17:38:41","modified_gmt":"2021-08-23T14:38:41","slug":"composing-functions-in-swift","status":"publish","type":"post","link":"https:\/\/railsware.com\/blog\/composing-functions-in-swift\/","title":{"rendered":"Composing functions in Swift"},"content":{"rendered":"\n<p>In Swift &#8211; the new programming language introduced by Apple &#8211; functions are first class citizens. This basically means, that a function can be passed as a parameter, returned from another function or assigned to a value. It allows us to do a lot of useful stuff with them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Function decorators<\/h2>\n\n\n\n<p>Let&#8217;s use the concepts of function as a first class citizen to implement some basic function decorator.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Assign functions to variables<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func greeting(firstName: String, lastName: String) -&gt; String {\n    return \"Hello, \" + firstName + \" \" + lastName + \"!\"\n}\nlet greetSomeone = greeting\nprintln(greetSomeone(\"John\", \"Doe\"))    \/\/ =&gt; Hello, John Doe!\n\n<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Functions can be passed as parameters to other functions<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func johnDoeFunction(function: (String, String) -&gt; String) -&gt; String {\n    return function(\"John\", \"Doe\")\n}\nprintln(johnDoeFunction(greeting))      \/\/ =&gt; Hello, John Doe!\n\n<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Functions can return other functions<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func composeHelloFunction() -&gt; (String -&gt; String) {    \n    func hello(name: String) -&gt; String {\n        return \"Hello, \" + name\n    }\n    return hello\n}\nlet helloFunc = composeHelloFunction()\nprintln(helloFunc(\"John\"))              \/\/ =&gt; Hello, John\n\n<\/pre>\n\n\n\n<p>This concept allows us to implement function decorators in Swift.<\/p>\n\n\n\n<p>Function decorators work as wrappers to existing functions, modifying the behavior of the code before and after a target function, without the need to modify the function itself. They augment the original functionality, thus decorate it.<\/p>\n\n\n\n<p>Using the concepts above let&#8217;s write a simple decorator that wraps the String output of another function by some html tag.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func hello(name: String) -&gt; String {\n    return \"Hello, \" + name\n}\n\nfunc bold(function: String -&gt; String) -&gt; (String -&gt; String) {\n    func decoratedBold(text: String) -&gt; String {\n        return \"<b>\" + function(text) + \"<\/b>\"\n    }\n    return decoratedBold\n}\nlet boldHello = bold(hello)\nprintln(boldHello(\"Vladimir\"))          \/\/ =&gt; <b>Hello, Vladimir<\/b>\n\n<\/pre>\n\n\n\n<p>We wrote a function that takes another function as an argument, generates a new function, augmenting the work of the original function, and returns the generated function so we can use it anywhere. Decorating function also allows us to insert some behaviour before\/after function call or combine multiple functions into one.<\/p>\n\n\n\n<p>In the example above we had to explicitly specify the signature of the function to decorate: <code>func bold(function: String -&gt; String)<\/code>. We&#8217;ve implemented bold decorator so that it decorates a function from one <code>String<\/code> value, which returns another <code>String<\/code> value. But what if one would like to create bold decorator which accepts functions with different signatures?<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Abstract Functor<\/h2>\n\n\n\n<p>Let&#8217;s define an abstract Functor class. By &#8216;Functor&#8217; let&#8217;s assume a class, which wraps any function and allows to call that function.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">class F&lt;T1, T2&gt; {\n    \n    let f: T1 -&gt; T2\n    \n    init(function: T1 -&gt; T2) {\n        self.f = function\n    }\n    \n    func run(args: T1) -&gt; T2 {\n        return f(args)\n    }\n}\n\n<\/pre>\n\n\n\n<p>This class allows us to wrap any function and call it somewhere:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func logger(text: String) {\n    println(\"LOG: \\(text)\")\n}\nlet loggerFunc = F(logger)\nloggerFunc.run(\"Hello\")    \/\/ =&gt; LOG: Hello\n\n<\/pre>\n\n\n\n<p>Using the Functor class we can now rewrite bold decorator to accept functions with different number of parameters:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func bold(function: F&lt;T1, String&gt;) -&gt; F&lt;T1, String&gt; {\n    func decoratedBold(args: T1) -&gt; String {\n        return \"<b>\" + function.run(args) + \"<\/b>\"\n    }\n    return F(decoratedBold)\n}\n\nlet boldGreeting = bold(F(greeting))\nprintln(boldGreeting.run(\"John\", \"Doe\"))    \/\/ =&gt; <b>Hello, John Doe!<\/b>\n\nlet boldHello = bold(F(hello))\nprintln(boldHello.run(\"Vladimir\"))          \/\/ =&gt; <b>Hello, Vladimir<\/b>\n\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Composing functions<\/h2>\n\n\n\n<p>Another interesting approach of using function decorators is composing several functions into single one.<\/p>\n\n\n\n<p>Swift allows overloading basic operators. Let&#8217;s try to overload <code>+<\/code> operator to accept two functions and compose them into one function.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func +&lt;T1, T2&gt;(beforeHook: F&lt;(), ()&gt;, function: F&lt;T1, T2&gt;) -&gt; (T1 -&gt; T2) {\n\n    func composedFunc(args: T1) -&gt; T2 {\n        beforeHook.run()\n        return function.run(args)\n    }\n\n    return composedFunc\n}\n\nfunc +&lt;T1, T2&gt;(function: F&lt;T1, T2&gt;, afterHook: F&lt;T2, ()&gt;) -&gt; (T1 -&gt; T2) {  \n \n    func composedFunc(args: T1) -&gt; T2 {\n        var result = function.run(args)\n        afterHook.run(result)\n        return result\n    } \n  \n    return composedFunc\n}\n\n<\/pre>\n\n\n\n<p>Above you can see two overloads of <code>+<\/code> operator which accept functors of different types and combine them into a single function.<br>The first overloaded version runs a <code>Void -&gt; Void<\/code> function before main function, and the second one runs main function,<br>then passes its result to another <code>T2 -&gt; Void<\/code> function and returns the result of the main function.<\/p>\n\n\n\n<p>Let&#8217;s write an example of using this approach:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func logger(text: String) {\n    println(\"LOG: \\(text)\")\n}\n\nfunc request(url: String) -&gt; String {\n    return \"Success 200\"\n}\n\nlet logRequest = F(request) + F(logger)\nlogRequest(\"http:\/\/some.awesome.url\")       \/\/ =&gt; \"LOG: Success 200\"\n\nlet composedRequest = F({ println(\"Request is fired!\") }) + F(request)\nprintln(composedRequest(\"http:\/\/some.awesome.url\"))\n\/\/ =&gt; Request is fired!\n\/\/ =&gt; Success 200 \n\n<\/pre>\n\n\n\n<p>We could also implement <code>+<\/code> operator overload for plain functions, not for Functor type, but overloading operators for basic types may be a bad practice.<\/p>\n\n\n\n<p>Another approach of composing functions may be implemented with some helper classes and without overloading operators. As an example of doing this<br>take a look at <code>Before<\/code> and <code>After<\/code> classes <a title=\"here\" href=\"https:\/\/github.com\/atermenji\/FunctionSwifter\/blob\/master\/FunctionSwifter%2FSwifter.swift\">here<\/a>. They allow us to compose functions in another way:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">let composedRequest = Before(request).run({ println(\"Request is fired!\") })\nlet loggedRequest = After(request).run(logger)\n\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Retry\/repeat function call<\/h2>\n\n\n\n<p>One another way of using function decorators and Functor class, implemented above, is to write Repeat and Retry decorators. It will allow to run a single function multiple times or until some condition is met.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">class F&lt;T1, T2&gt; {\n    \n    ...\n    \n    func repeat(args: T1, times: Int) -&gt; T2 {\n        for i in 1..times {\n            f(args)\n        }\n        return f(args)\n    }\n\n    func retry(args: T1, maxTries: Int, condition: () -&gt; Bool) -&gt; T2 {\n        var tries = 0\n        var result: T2?\n        \n        while !condition() &amp;&amp; tries &lt; maxTries {\n            result = f(args)\n            tries++\n        }    \n    \n        return result!\n    }\n}\n\n<\/pre>\n\n\n\n<p>Code above allows us to implement multiple calling of a function mechanism like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">func greeting(firstName: String, lastName: String) {\n    print(\"Hello, \" + firstName + \" \" + lastName + \"!\")\n}\n\nF(greeting).repeat((\"John\", \"Doe\"), times: 3)    \/\/ =&gt; Hello, John Doe! Hello, John Doe! Hello, John Doe!\n\n<\/pre>\n\n\n\n<p>Or we can run a function until some condition is met or until we have performed some number of tries:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted toolbar:1 lang:swift decode:true\">var requestResult: Int = 0\nfunc randomRequest(url: String) {\n    let result = Int(arc4random_uniform(UInt32(2)))\n    if result &gt; 0 {\n        requestResult = 200\n    } else {\n        requestResult = 404\n    }\n}\n\nF(randomRequest).retry(\"http:\/\/some.awesome.url\", maxTries: 5, condition: { requestResult == 200 })\n\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>This article demonstrates a basic approach of decorating and composing functions in Swift. It is pretty easy to implement Decorator pattern in Swift and many useful decorators may be implemented using the described approach.<\/p>\n\n\n\n<p>Having functions as first class citizens may allow creating clean, short and extensible code, which will be pretty easy to understand.<\/p>\n\n\n\n<p>All the code examples for this article could be found in this <a title=\"repository\" href=\"https:\/\/github.com\/atermenji\/FunctionSwifter\">repository<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Swift &#8211; the new programming language introduced by Apple &#8211; functions are first class citizens. This basically means, that a function can be passed as a parameter, returned from another function or assigned to a value. It allows us to do a lot of useful stuff with them. Function decorators Let&#8217;s use the concepts&#8230;<\/p>\n","protected":false},"author":58,"featured_media":14237,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[3],"tags":[],"coauthors":["Artur Termenji"],"class_list":["post-6968","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"aioseo_notices":[],"categories_data":[{"name":"Engineering","link":"https:\/\/railsware.com\/blog?category=development"}],"post_thumbnails":"https:\/\/railsware.com\/blog\/wp-content\/themes\/railsware\/vendors\/images\/article-thumbnail-default.jpg","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/6968","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/users\/58"}],"replies":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/comments?post=6968"}],"version-history":[{"count":23,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/6968\/revisions"}],"predecessor-version":[{"id":13964,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/6968\/revisions\/13964"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/media\/14237"}],"wp:attachment":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/media?parent=6968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/categories?post=6968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/tags?post=6968"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/coauthors?post=6968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}