All Sorted

Part of our job as developers is taking in a large amount of information and parsing it down to the components needed. I’ve always loved filtering and sorting through lists whether in excel or Salesforce or other content management systems. In my previous jobs, it was common to get a request like “We need a list of all the donors who gave more than $10,000 in the 2013 Fiscal Year under the age 45.”  or “We need a list of 8th graders who live in Brooklyn.” I would then use a series of filters to parse down a database of donors or students into a usable result like a list of names and mailing addresses.

This post is a short cheatsheet on how to sort through data in dictionaries and arrays in Swift. In a future post, I will cover the unique steps needed to filter through JSONs.

Types of Sorting
Based on the information you have and what you need, there are different methods you can use to get your desired output. Below are some helpful methods to have in your toolbox when dealing with dictionaries.

filter: Greater Than or Less Than
//Greater Than or Less Than
var rentPerMonth = [["rent" : 2200], ["rent" : 2350], ["rent" : 2300], ["rent" : 2490]]
var filteredRent = rentPerMonth.filter({
$0["rent"] < 2000
})
print(filteredRent)

This will display an empty array.

filter: Used for

//Select nonchanging values like neighbordhoods – Good for buttons
let neighborhoods: NSArray = ["Crown Heights", "Clinton Hill", "Sunset Park"]
let fiteredNeighborhoods = (neighborhoods as! Array).filter { $0 == "Sunset Park" }
print(fiteredNeighborhoods)

view raw
Filter by Keyword
hosted with ❤ by GitHub

containsString: Search by Keyword

//Search by Keyword
let savedApartments = [
"apt1" : "The unit comes with stainless steel appliances, a full-sized refrigerator, plenty of storage, a gas oven, a gas range, and a dishwasher.The bedroom has hardwood floors and a window that opens.", "apt2" : "you will love it", "apt3" : "So many great amenities"]
for (name, description) in savedApartments {
if description.containsString("a window that opens") {
print(name)
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s