As a C# developer, I spend way too much time filtering lists of stuff and transforming it into other stuff. Luckily enough, C# cones with Linq (Language integrated query) which lets me do complex filtering and transformation of data. No such luck with SWIFT.
It turns out I can do the same thing with SWIFT, after all. Using a combination of filter and map I get to filter and map my data just as I would with Linq.
Lets work on an example. I have an adventure game with has items in it. An item has a lot of properties, one of which is the location of the item. If the item is being carried, then it has a special location called "ROOM_CARRIED". So my first job is to get a list of all of the items that I am currently carrying.
let carriedItems = items.filter { $0.Location == ROOM_CARRIED }
item
is my array of items. It comes with a pre-defined method called filter
and filter
takes a closure to tell it what to do. In the above code, we have a reference to the object being filtered
via the $0 variable. Each item will be passed in, one at a time, and the closure will return true or false
indicating whether the item matches our filter criteria.
In this case, we check the item location to see whether it matches the ROOM_CARRIED special
location. carriedItems
will end up as an array of items the we are carrying.
So far, we have half a job. What I actually want is an array of the descriptions of the items so I can present it to the user. What I have is an array of items. Next job then is to transform the items into their descriptions.
let carriedItems = items.filter { $0.Location == ROOM_CARRIED }
.map {$0.ItemDescription}
So, same filter operation as before but I've added an .map
to it. .map
is just like filter in that it
takes a closure and, as with all closures, it is passed it's parameter in the $0 variable. What we return
is what we want the input object transformed into, In this case, I want the description of the item
so I can just return the ItemDescription
property of the item instance passed to the closure.
So my return type is an array of strings.