{"id":406,"date":"2014-07-19T10:01:25","date_gmt":"2014-07-19T16:01:25","guid":{"rendered":"http:\/\/dev.iachieved.it\/iachievedit\/?p=406"},"modified":"2014-07-19T10:01:25","modified_gmt":"2014-07-19T16:01:25","slug":"swift-arrays-and-closures-for-mapping-and-filtering","status":"publish","type":"post","link":"https:\/\/dev.iachieved.it\/iachievedit\/swift-arrays-and-closures-for-mapping-and-filtering\/","title":{"rendered":"Swift Arrays and Closures for Mapping and Filtering"},"content":{"rendered":"<p>I like <a href=\"http:\/\/www.erlang.org\/\">Erlang<\/a>, though I can&#8217;t claim to be proficient in it.  I haven&#8217;t even written a &#8220;real&#8221; program in Erlang yet, but I still enjoying working with it.  The other night I was going back through the excellent online book <a href=\"http:\/\/learnyousomeerlang.com\">Learn You Some Erlang for Great Good<\/a> and started working with <i>list comprehensions<\/i>.  In short, a list comprehension in Erlang is about &#8220;building sets from sets.&#8221;  Observe:<\/p>\n<pre>\r\n[2*N || N <- [1,2,3,4]].\r\n<\/pre>\n<p>This whacky looking code takes the list <code>[1,2,3,4]<\/code> and creates a new list by binding each element to the variable <code>N<\/code>, and then applying the function <code>2*N<\/code>.  The result is a new list:  <code>[2,4,6,8]<\/code>.  You can even do something like convert an array of temperatures given in Celsius to Fahrenheit:<\/p>\n<pre>\r\n[C*(9\/5)+32 || C <- [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]].\r\n[32.0,50.0,68.0,86.0,104.0,122.0,140.0,158.0,176.0,194.0,\r\n 212.0]\r\n<\/pre>\n<p>Slick.  Of course, this is a Swift tutorial, so obviously you can do the same thing in Swift, and let's face it, in a much more readable syntax:<\/p>\n<pre>\r\nvar temperatures:Array<Double> = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\r\ntemperatures.map({(c: Double) -> Double in\r\n  return c*(9\/5)+32\r\n})\r\n<\/pre>\n<p>Granted, this is a bit more verbose than the Erlang example, but if you've read any of our other posts you will know we're a big fan of verbose (also known as readable) code.  For those that appreciate a bit more compact form though, you can do:<\/p>\n<pre>\r\ntemperatures.map({c in c*(9\/5)+32})\r\n<\/pre>\n<p>The second form is a \"single statement closure\" that implicitly returns the value of its only statement, and we can omit naming the parameter type and return type.  The parameter type is implied as <code>Double<\/code> since we are mapping over an <code>Array&lt;Double&gt;<\/code>.  Our return type will be promoted to a <code>Double<\/code> as well.<\/p>\n<p>Of course we aren't limited to numbers here, we can supply an array of tuples of <code>Point<\/code>s and output the distance of each point from the origin (0.0, 0.0).  <\/p>\n<p>[objc]<br \/>\nimport Foundation<\/p>\n<p>typealias Point = (x:Double, y:Double)<\/p>\n<p>var points:Array&lt;Point&gt; = [(1,1), (1,2), (-1,-1), (-1,-2)]<\/p>\n<p>println (points)<\/p>\n<p>var distances = points.map({<br \/>\n    (x,y) in sqrt(pow(x,2) + pow(y,2))<br \/>\n    })<\/p>\n<p>println(distances)<br \/>\n[\/objc]<\/p>\n<p>Note the elegance in <code>(x,y) in<\/code>.  Each tuple element yielded to our closure is bound to <code>(x, y)<\/code>, thus allowing us to calculate the distance of the point from the origin using the standard [math]d=\\sqrt{(x^2 + y^2)}[\/math] formula.<\/p>\n<p>Of course, we aren't limited to using <code>Array.map<\/code> with just numbers, you can operate on any data type you like.<\/p>\n<p><code>map<\/code> isn't the only nifty <code>Array<\/code> function.  Take a look a this Erlang code (we're borrowing the example from Learn You Some Erlang):<\/p>\n<pre>\r\n[X || X <- [1,2,3,4,5,6,7,8,9,10], X rem 2 =:= 0].\r\n[2,4,6,8,10]\r\n<\/pre>\n<p>Once again, Erlang takes the top prize for odd-looking syntax.  The <code>[X || X <- [1,2,3,4,5,6,7,8,9,10]<\/code> looks familiar, but it's followed by <code>, X rem 2 =:= 0].<\/code>.  This is secret code for \"supply only elements that are divisible by 2\" thus the right half after the comma is a <i>filter<\/i>.  Well, Swift can filter too!<\/p>\n<pre>\r\n$ swift -repl\r\nWelcome to Swift!  Type :help for assistance.\r\n  1> [1,2,3,4].filter({x in x % 2 == 0})\r\n$R1: Int[] = size=2 {\r\n  [0] = 2\r\n  [1] = 4\r\n}\r\n<\/pre>\n<p>Very handy.  We can also chain <code>map<\/code> and <code>filter<\/code>, like this:<\/p>\n<pre>\r\n  2> import Foundation\r\n  3> [1,2,3,4,5,6,7,8,9,10].filter({x in x % 2 == 0}).map({x in pow(x,2)})\r\n$R7: CDouble[] = size=5 {\r\n  [0] = 4\r\n  [1] = 16\r\n  [2] = 36\r\n  [3] = 64\r\n  [4] = 100\r\n}\r\n<\/pre>\n<p>This code filters out the odd numbers from the array and then squares the remaining items.  Or put another way it squares even numbers between 1 and 10.<\/p>\n<p>The Swift <code>Array<\/code> generic (yes, it's a generic) has a number of other hidden gems.  Be sure and check out the Swift <a href=\"https:\/\/developer.apple.com\/library\/prerelease\/ios\/documentation\/General\/Reference\/SwiftStandardLibraryReference\/Array.html\">Standard Library Reference<\/a> for more information.<\/p>\n<p>Now, if only Swift would incorporate Erlang's <a href=\"http:\/\/www.erlang.org\/documentation\/doc-5.6\/doc\/programming_examples\/bit_syntax.html\">bit syntax<\/a>.  <i>That<\/i> would be cool.<\/p>\n<p><b>Editors Note:<\/b>  You may notice we don't show examples in the Xcode playground but rather use the Swift REPL interpreter from the command-line.  For details on how to do this see our <a href=\"http:\/\/dev.iachieved.it\/iachievedit\/?p=336\">previous post<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I like Erlang, though I can&#8217;t claim to be proficient in it. I haven&#8217;t even written a &#8220;real&#8221; program in Erlang yet, but I still enjoying working with it. The other night I was going back through the excellent online book Learn You Some Erlang for Great Good and started working with list comprehensions. In [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-406","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/406"}],"collection":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/comments?post=406"}],"version-history":[{"count":19,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/406\/revisions"}],"predecessor-version":[{"id":425,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/406\/revisions\/425"}],"wp:attachment":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media?parent=406"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/categories?post=406"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/tags?post=406"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}