Monday, November 7, 2016

Harry Doyle & Xcode iOS Application Templates

Using Xcode to build your application is like joining a baseball team that already has a stadium, groundskeepers, uniforms, a team plane, a roster, a working scoreboard, and a couple questionable announcers.



Xcode, in other words, supports you with pre-existing code that does a bunch of stuff that you'll need to make your application function. Xcode will provide some starter building blocks for you to build your application off of. In other words, you will not need to build your apps completely from scratch.

That being said, you do not have to use all the building blocks that Xcode gives you. You can keep some and delete others as you see fit. The more you play with Xcode and get a feel for what it offers and what you need, the better you'll be able to decide to keep or toss the building blocks Xcode gives you.

Upon choosing to create a new project, you are quickly asked to choose one of the following five templates to base your new app on:



Specifically, you can build a Master-Detail Application, a Page-Based Application, a Single View Application, a Tabbed Application, or a Game. In this post, we'll run through the differences between them all so you have a better idea which to choose when starting to build your app.

Let's say you want to build that bullpen phone app that we discussed in the last post; the one where you are the manager and you get to choose which relievers from the bullpen to warm up and how quickly they need to get ready before actually making the call.

What will the app need to do? First, it needs to list all of your relievers. Second, it needs to let you choose up to two relievers to warm up. Third, it needs to let you review the stats of your relievers so you can make an informed decision. Fourth, the app needs to let you indicate how quickly the relievers are needed. And fifth, a way for the bullpen coach to communicate when the relievers are ready to enter the game.

Which of the above application templates should we use for our bullpen app? Let's run through the options.

1) Master-Detail Application

Between Apple's icon for Master-Detail and the brief description towards the bottom of the above image which reads, "This template provides a starting point for a master-detail application, using a split view controller to display a list of items and a detail view", we can make an educated guess on how Master-Detail works: Master-Details offers a column of items on the left and when we choose one of those items we then see it in greater detail in the larger space on the right.

Does this approach work for our bullpen phone app? Let's see.

In the bullpen phone app we can have master segments that cover: bullpen pitchers, pitcher stats, and ready pitchers. If we choose bullpen master, in the detail section we see a list all of our relief pitchers (for example, Betances, Clippard, Warren, Severino, Shreve, Layne). We can then choose up to two pitchers, indicate how quickly we need them to get ready, and make the call to the bullpen. If we need to review Warren's stats before making the call, we can tap the pitcher stats segment, choose Warren from the list of relievers and see his latest games log. If we have already chosen two pitchers to warm up and check their progress, we can tap the ready pitchers segment and see if the pitchers are ready or not, before choosing the one we want to go with. Which you gotta believe will have a confirmation GIF of a manager walking out to the mound raising his left or right arm and tapping it with the other.

But what if it's the seventh inning and we want to get up Adam Warren and Tommy Layne, a righty and a lefty, just in case the other team brings up a pinch hitter? Can we choose two relievers from the left-hand column and display them both simultaneously in the detail screen on the right? Unfortunately, we cannot in this setup.

So Master-Detail may not be for us this time.

When is a good time to use the Master-Detail Application template?
Master-Detail is particularly helpful for iPad applications as it provides a split-screen look that Tabbed Applications do not.

On to the next option.

2) Page-Based Application

Here too, Apple's icon for the template and their explanation give a glimpse into how a Page-Based Application works. Apple explains that this template, "provides a starting point for a page-based application that uses a page view controller."

From looking at the icon and seeing its three dots we can deduce that that app has three screens that we can swipe through. As a point of reference, the most popular example of a Page-Based Application is your iPhone itself: From the home screen you can swipe through all the different pages of apps that you have on your phone. In this case, the number of apps that you have on your phone that can fit on a screen will determine how many screens you'll swipe through.

Does the Page-Based Application template work for our bullpen phone app? Not so much. Page-Based apps are best for portfolio sites that want to show off information, such as images, rather than process information through functions that require user input.

So Page-Based is not for us either this time.

When is a good time to use the Page-Based Application template?
Page-Based applications are best for where you can read books or articles that have multiple pages in lieu of vertical scrolling.

3) Single View Application

While the Single View Application icon may not tell us much about how this template works, Apple's explanation helps: "This template provides a starting point for an application that uses a single view. It provides a view controller to manage the view, and a storyboard or nib file that contains the view."

Many apps are built on the Single View template. Why? Because it offers a lot of flexibility in terms of layout of images, text, buttons, and more. And it's not like you only have one screen to build your entire app on. Rather, you have as many individual views (or screens) as you need to build your app. Each view is a different screen and each screen is a different view controller.

Does the Single View Application template work for our bullpen phone app? It just might. Let's walk through it. On the Home screen we could create a table of all of our relievers, checkmark those we want to warm up, and then press a "Warm Up" button on the bottom to make the call. That works pretty well. If we want more information about a reliever, say a log of all the games he's pitched that season working backward by date, we can click on the reliever's name and go to a different screen (view controller) that provides that information. After making the call we can have another screen that asks the manager how quickly each reliever needs to warm up ranging from Next Inning to Next Batter. (We might even want to build this functionality into the first screen or make it like a checkout process where you pick what you want, confirm, pay).

The Single View template works well for our needs, but let's take a look the remaining two templates just in case they are even better.

4) Tabbed Application

Again, the Tabbed Application template icon isn't completely helpful and while Apple's description, "This template provides a starting point for an application that uses a tab bar. It provides a user interface configured with a tab bar controller, and view controllers for the tab bar items" helps, we can do better.

Do you use Instagram? Instagram is a Tabbed Application. How do we know? Along the bottom of the Instagram app are five tabs: home, search, camera, favorite, and profile. Tap any one of these tabs and you are quickly taken to that screen.

Is this a good approach for our bullpen phone app? Depends. What tabs would we need? We could have a Roster tab where we could see all of our relievers. We could have a Warming Up tab where we could see who is currently getting ready in the bullpen. We could also have a Stats tab where we can select specific relievers to see how they've done so far this season and how much they've worked lately.

So far the Single View and Tabbed Application templates may be our best bets for this particular app.

5) Game Application
So far we haven't thought of the bullpen app as a game because when your starter loads the bases the manager doesn't usually have time to spare: He needs to notify the bullpen immediately.

But could we turn this into a game? Sure we can. What would the game look like? You're the manager and you have to navigate your team through a treacherous seventh inning in which your starter starts the inning at 90 pitches thrown and the meat of the order is coming up. Can you, as manager, pull the right levers to keep your one run lead? That could be a game version of the bullpen app.

And that, in general, are your different application template options when looking to build your own app through Xcode.

Tuesday, October 25, 2016

Xcode Libraries & Frameworks: The Don't Call David Ortiz Episode


In the latter innings of a baseball game, there is no confusion over who calls who: The manager calls the bullpen. Question is, which pitcher(s) in the bullpen is the manager calling for and how quickly do the relievers need to get ready? 

It's questions like this that get developers thinking about new apps and what steps to take to build them. In our manager's case, he needs an app that calls the phone number of the bullpen phone, an app that displays on the bullpen phone screen images of the pitchers he wants to get ready, and indicates how quickly he wants them to get warmed up (maybe on a scale from next inning to next batter).  

If we were to build out this bullpen app we would have to navigate Xcode appropriately.  

Oh, and if David Ortiz calls the bullpen he's not much of a conversationalist. He prefers to let his bat do the talking.



Xcode may be most well-known for its ability to write software for Apple's iPhone OS (Operating System), but that's not all Xcode can create software for. In fact, with Xcode you can write software for iOS, watchOS, tvOS, OS X, and the always popular "Other". Not only can you create applications for each of these operating systems (OS), but you can also write frameworks, libraries, and system plug-ins for OS X. 

That's all great, but what does it all mean, why are libraries and frameworks important, and when do we use which? That's what we'll cover in this post as we dig a little deeper into Xcode.

Getting Started with iOS
When it comes time to start a new project Xcode gives you some options. Do you want to create something for the iPhone (iOS), for the Apple watch (watchOS), Apple TV (tvOS), for a Mac laptop or desktop (OS X), or something else? These options appear on the left hand side of this window:


In the above case, we see our iPhone application options. In the same way that a baseball clubhouse manager makes sure that all the uniforms are cleaned and hanging in each player's locker ready for the game, Xcode lays out some pre-existing software formatting for each format before we even write a line of code. If you're familiar with Ruby on Rails, it's akin to Rails scaffolding. Do you need it all? Maybe. Maybe not. Either way, it's there if you do. Specifically, Xcode comes with established code for apps that are Master-Detail, Page-Based, Single View, Tabbed, or in Game formats. 

What are frameworks and libraries? And how are they different?
A good question with, apparently, no single answer as this Stack Overflow page notes. Seeing how this is our first time with this subject, let's take a broad view for now. This visual representation of frameworks and libraries may help:



So what's going on here? Let's walk through it. Say that you're a manager building an iOS app that wants to keep track of your bullpen (the green "Your Code" rectangle above).

A framework is made up of one or more libraries. Libraries are pre-existing code that you call to use their functionality instead of building out that functionality yourself. A manager can go out and try to pitch the ninth or he can pick up the bullpen phone and call for the closer who already knows what he's doing and does it much better than the manager.

In the same way, your code calls a library when it needs to use that library's code. Here are some of the most popular Swift libraries currently found on the online code repository, GitHub:



A framework, on the other hand, calls your code (the way that Zack Britton probably tried to call Buck Showalter during the 2016 AL Wild Card game; that phone may still, in fact, be ringing...). Why, or more importantly, when would a framework want to call your code?

Broadly speaking, a framework calls your code when it needs to know what to do with what it has. Here are a few examples:



Those all sound great, but what are they talking about? Good question. In general, what Ben's talking about is this: The user of your app, in this case, the manager, chooses a reliever from the bullpen and calls him. Then what? Then the framework takes that information - that the app needs to call a specific reliever in the bullpen - and calls your code to find out what to do with the manager's action. In our case, the framework learns from your code that the headshot of the chosen reliever should appear on the screen of the bullpen phone.

That's the big picture of what it means for a framework to call you. In other words, the framework's not calling you, it's calling the code you wrote so the framework knows how to properly respond to an event in your app. The Hollywood paraphrasing that some software bloggers and teachers have adopted to explain frameworks ("Don't call us, we'll call you.") is cool, but potentially confusing. Hopefully this explanation clears things up.

Here is a long list of frameworks that come with iOS-based devices.  The list includes frameworks that allow users to access their address books, for determining a user's location, and for accessing a user's calendar for event data among others.

Our manager can even create his own frameworks and distribute them if he wants so teams from Rookie ball to the majors can use the technology.

On Deck: We'll continue to delve into Xcode.



Monday, September 26, 2016

Yankee Stadium is to Ballparks As Xcode Is to IDEs

Before we jump into enumerations' cousins, structures and classes, let's discuss the ballpark where all the Swift games are played: Xcode.

To this point, all the code that I've written for this blog I wrote in an Xcode playground. A playground, as the playground likes to tell people when they first open it, looks like this:



In other words, a playground is a place where you can play with or practice writing some code to make sure if it works before writing it into your final project.

Why can't we just play around with stuff in our final project? Oh, you can and you will. But sometimes you'd rather practice that Jeter jump-throw on the playground behind an abandoned building than during Game 1 of the ALCS on national television.


So what is Xcode? Xcode is Yankee Stadium, Wrigley Field, Fenway Park. It's where you code the apps that will one day exist in the App Store. Unlike playgrounds which exist as is, Xcode has the ability to include files from your hard drive, to reach out to the web, and more. Playgrounds are games of pepper: Xcode is a full nine and extras if necessary.

If Wrigley is a ballpark, Xcode is an IDE. What is an IDE?  It is an Integrated Development Environment which is a fancy way of saying it's where you code software. Here's Wikipedia's definition:


And to give you a visual, here is Sublime Text 3, a popular text editor, where a developer would normally write code:


What you see here is code written in Python. And here is Swift code written in Xcode:


What similarities and differences do you see? Let's start with similarities. Both have examples of code written in them. In Sublime Text, all you see is code. In Xcode, you see code in the second panel from the right. 

And the differences? The biggest difference is what the other three panels in Xcode can do for you that regular text editors do not. 

On the far left panel there is a list of all the different files created for this project, these include assets such as images, videos, and sound files, it includes the storyboard which is what you see in the panel second from the left which acts as a visual of what you are building. It includes the actual files where you write code like what you see in the panel second from the right. And that just covers the highlighted blue folder in the upper lefthand corner of Xcode. To the right of that highlighted blue folder are seven more icons adding even more functionality from what errors or warnings there are and what they have to say, to a search function to find whatever it is you may be looking for, to the break point navigator that details where you have installed specific areas where the code should stop running so you can identify bugs. 

In short, text editors are like pitchers that strike out or walk everyone and IDEs like Xcode are pitchers that make use of their fielders to save their arms. Or what Crash Davis told Nuke here:




So relax. This game is fun goddammit. It's fun.

Going forward we are going to dig deeper into Xcode before returning to structures and classes.

Thursday, September 22, 2016

The Associated Values of Kershaw's Pitches & Yankee Closer Lineage as a Recursive Enum (Sexy Long Title Post)

In our last post we went nine innings on enums. Today we'll go into extras as we cover associated values and recursive enumerations.

Enums and Associated Values
In previous raw value examples we either let the computer infer certain values (If Kershaw is 1, Maeda is 2) or we assigned specific values (case Kershaw = 0.579). But what if we know what kinds of types we'll need (Strings, Ints, Bools, etc), but don't have the exact values yet? Then we can use associated values.

Let's say we want to breakdown Kershaw's pitches to Posey by pitch type. Here's an example:



What's going on here? First, we create an enum called KershawPitch and a case for each of his three pitches, Fastball, Curveball, and Slider. Then we setup our associated values for each pitch. In this case, we'll focus on the number of each pitch he throws (that is, the count) and the average velocity of that kind of pitch (averageVelocity). That's how to setup associated values for an enum.

To access these associated values, we'll use pattern matching which we'll address along with other popular patterns in a future post.


Recursive Enumerations
First off, what does recursive mean?



In the same way that an infinite loop can crash a program (or a computer!), something that is recursive can also repeat itself indefinitely to the detriment of your program, namely by hogging up an undetermined amount of memory. Fortunately, there is a way to avoid this through recursive enumerations.

Why are recursive enums important?
Statistics in baseball give us a good idea of what to expect from players. That is, until they put up numbers that seem odd compared to the rest of their stats. Recently, Ivan Nova put up numbers with the Pirates that were significantly better than the ones he put up with the Yankees earlier that same year (2016).

After eight great starts with the Pirates (ERA under 3.00, WHIP under 1.00), I picked Nova up for my fantasy baseball team against the Reds. In three innings the Reds lit Nova up for 10 hits and four earned runs. I was ready for certain good numbers (ERA under 3.00, WHIP under 1.20) and certain bad numbers (4.50 ERA, 2.00 WHIP), but as the Reds hit around I wondered, "When is this going to stop? Or are the Pirates going to hang him out there to dry even if he gives up 10 runs?" Not good! Fortunately, they pulled him after three innings to stop the bleeding.

In terms of coding, for each app that you write there is a Swift compiler. Among other functions, the compiler reviews the code you've written to determine how much memory that code will require. When it comes to enums, the compiler reviews the enum's different cases and assesses how much memory each case will require. Sometimes the compiler finds cases that require an uncertain amount of memory; an uncertain amount that may be very large leading to slow load times and performance. As an example, let's consider the line of closers for a team over time.




So we've set up our LineOfClosers enum with two cases; a case where we remember who the predecessor is and a case where we don't remember who the predecessor is. Seems harmless enough. But we already have an error. The error, "Recursive enum 'LineOfClosers' is not marked 'indirect'". This doesn't explain what is wrong so much as how to solve the error which we'll get to in a minute.

So let's talk about why Xcode throws the error in the first place. Like Ivan Nova's expanding ERA versus the Reds above, Xcode feels good about how to allocate memory for KnownPredecessors that have a name which is a string, but it doesn't feel good about the predecessor which is a LineOfClosers data type. Why? Because Xcode just sees a black box and has no idea what is in it.

Unfortunately, neither do we, but there is a way to handle the issue. To solve the problem we use a pointer which is a form of indirection. Here's how The Big Nerd Ranch Guide to Swift Programming explains it, "How does using a pointer solve the 'infinite memory' problem? The compiler now knows to store a pointer to the associated data, putting the data somewhere else in memory rather than making the instance of [LineOfClosers] big enough to hold the data. The size of an instance of [LineOfClosers] is now 8 bytes on a 64-bit architecture - the size of one pointer." In other words, we make the uncertain certain by defining its size as 8 bytes rather than an unknown amount of bytes.

Ok, so how do we make use of this indirection in our example? We do it by using the indirect keyword like this:




In fact, we can get a little more precise by marking individual recursive cases as indirect like this:





Let's play around with filling out the YankeeClosers enum.



Dellin Betances is the Yankees' current closer. Before him came Andrew Miller, Aroldis Chapman, David Robertson, Mariano Rivera, Rafael Soriano (the year Mo was injured), Rivera, and John Wetteland, and then I don't remember off-hand so we assign ".NoKnownPredecessor" after Wetteland.

Monday, September 19, 2016

Buster Posey, the Dodgers Rotation, and Enums

Earlier we went over the major data types, the Strings, Ints, Floats, Doubles, and Bools of the Swift programming world. These data types can cover a lot of ground and handle a lot of different situations, but they can be like fitted caps inherited from older siblings: Nice to have, but they don't quite fit as well as one that is your actual size.



That's where enumerations, classes, and structures come in. They are data types that you can customize in Swift. We'll start off with enumerations, aka, enums.

What is an enum?
An enumeration - or enum - is akin to its meaning:



Now let's talk a closer look at what this meanings in terms of Swift coding.

In a previous post, we talked about switch statements and how we used switch statements if we thought that there were multiple different outcomes to a function. The example we used was of Grady Little going out to visit Pedro Martinez in 2003 and how Little could stick with Pedro, pull Pedro for a righty, pull Pedro for a lefty, or pull Pedro for a knuckleballer. We also included a default which is required for switch statements: "Call up Bobby Valentine for an emergency mustache and shots at Stan's."

Unlike switch statements, enums do not require defaults.

Why are enums important?
At first glance, especially with other options such as switch statements, classes, and structures, it isn't exactly clear what makes enums so important. For the best explanation, I'm going to hand it over to a Quora response from Brent Royal-Gordon who puts it like this:



When do we use enums?
If switch statements are particularly good at handling potentially open-ended circumstances or cases thanks to its default option, then enums are particularly good at handling well-defined cases.

Let's take a look at how Buster Posey hits against the 2016 Dodgers Rotation of Clayton Kershaw, Kenta Maeda, Rich Hill, Julio Urias, and Ross Stripling.



Here we've created a DodgersRotation enum using the enum keyword first and then capitalizing the name of the enum. After opening up some curly brackets we set out our different Dodger starting pitching cases from Kershaw through Stripling. Then we close up our enum with the second half of the closed curly brackets on line 11.

Let's start with how Posey does against Kershaw. On line 13 we create a variable, busterVersusDodgersRotation and define it not as a String or Int, but as a DodgersRotation data type. To focus on Kershaw, we choose the Kershaw case of the DodgersRotation enum (ie, DodgersRotation.Kershaw). Because we've selected the Kershaw case, line 19 prints out on the right. Hitters have a career .566 OPS against Kershaw so Buster is slightly above average.

But what if you don't want to keep updating Posey's OPS in the case print out statement? Can't we just set whatever Buster's OPS is to the proper pitcher's case and then use string interpolation to print it out in the print statement? Yes, we can. Check it out.



So we set Buster's OPS values against each Dodger starter up top in the enum case by case. Once we do that and setup string interpolation in the switch statement, the OPS figures print out on the right (line 20). So far, Maeda's done a nice job against Buster.

Enums and Raw Values
Enums can also store raw values. According to Swift documentation, "enumeration cases can come pre-populated with default values (called raw values), which are all of the same type." That's nice, but what does it mean? Let's take a look:



Let's say we wanted to assign numbers to the Dodgers starters, starting with their #1, Clayton Kershaw. First, we declared that the DodgersRotation enum would be an Int. Then we assigned a value to the first case, in this case 1 to Kershaw. Then, in line 13 we called the rawValue of Kenta Maeda and in line 14 we got 2. But we never explicitly assigned 2 to Maeda. How did it do that? That's the power of raw values in enums.

We can also use raw values with Strings.



By declaring the DodgersRotation enum to be a String on line 5, the computer knows that each case will also be a String so when we call the Urias rawValue on line 14 it knows to print out the value "Urias" when we call for it through string interpolation. It automatically assigns the name of the case to be a String of the same name. case Urias = "Urias".

Now, if we want case Kershaw to be "Clayton", we will have to write, case Kershaw = "Clayton". At that point, the computer won't know what to assign the rest of the Maeda, Hill, Urias, and Stripling cases unless it is personally on a first name basis with the rest of the Dodgers' rotation.

Enums and Methods
What else can we do with enums? We can run methods on the enum types we create. Let's use methods to find out Buster Posey's OPS differential against two different Dodger pitchers, Clayton Kershaw and Ross Stripling.



Let's walk through this. First, we created the Posey enum which gives us the Posey data type that we'll run our method on on line 32. Next we'll create two different cases, the Kershaw case and the Stripling case as we'll put up Buster's numbers against each. Then we'll create a function, opsDifferential,  that subtracts Buster's career OPS (.849) from whichever pitcher case he's facing, Kershaw or Stripling. Because OPS uses decimals, we'll use Doubles to handle whatever OPS versus either Kershaw or Stripling that Buster has and for whatever the outcome of the equation will be.

On line 22 we declare a switch on a self. What is self? Self is not an easy concept as it gets rather abstract rather quickly. In this case, self refers to the Posey enum. So can we write "switch Posey" and get away with it as if they are synonymous? Good question.  Let's try. Here's what happens:



Basically, Xcode can take "switch Posey", but then it wants us to pass an argument in those parentheses (line 22). Unfortunately, we have nothing to pass and even if we left the parentheses empty Xcode will throw errors noting that it has no accessible initializers. In other words, Xcode wants a lot more from us than we need to give it to do what we need to do. Ergo, writing "switch self" is preferable as it references the Posey enum without having to worrying about all the other stuff.

Back to line 23! What do we want our function to do? We want it to figure out the difference between Buster's career OPS and his OPS against a specific pitcher, in these cases either Kershaw or Stripling.

Outside and below the differential function, we then create a new variable, the vsKershaw variable on line 32. To the vsKershaw variable we run the Kershaw method on the Posey enum data type. Posey.Kershaw has a lot of shorthand built into it so let's unpack it for a minute. Posey.Kershaw is a quick ways of saying, "Run the Kershaw method, that is, subtract Buster's career OPS of 0.849 from his OPS against Kershaw."

But wait! You say. We haven't told the computer what Buster's OPS against Kershaw is yet! You're right. Let's do that on line 33 where we'll create a variable, opsVsKershaw, and assign Buster's current career OPS against Kershaw (0.529) to opsVsKershaw.

So what do we have? We have a Kershaw method on a Posey enum set to the vsKershaw variable and we have Buster's career OPS versus Kershaw set to the opsVsKershaw variable. Now what?

So we have all the parts, now we need to put them together to make the function go. That's what happens on line 35. Line 35 reads like this, "Run the Kershaw method (as opposed to the Stripling method) on the Posey enum through the opsDifferential function which subtracts Posey's career OPS from his OPS versus Kershaw." That's a bit of a mouthful, but hopefully it makes more sense to you than opsDifferential = vsKershaw.differential(opsVsKershaw).

On line 36 we tell the computer to print our results to the console using string interpolation which prints out, "Posey's OPS against Kershaw is -0.320 compared to his career OPS of .849."

As you can also see through this particular example, it is important to name things that make sense to not only you, but to other developers who may look at the code in the future. If you name things appropriately others should be able to read your code and make some sense of it.

That's a good start on enums. We'll do more in the next post.

Special thanks to Benedikt Terhechte who did a thorough job of explaining enums and raw values here

Challenge: Run through the examples above with a different hitter against different pitchers. Baseball-Reference.com is good at providing stats.

On Deck: Associated values and pattern matching in enums.



Thursday, September 8, 2016

Retired Numbers & The Set Collection Type

There's only one Willie Mays. There's only one Juan Marichal. There's only one Jackie Robinson. And because they were such good baseball players they got their numbers retired by the Giants, Dodgers, and major league baseball. They are unique.



And sometimes you just need one of something. When it comes to Swift collection types, if you want one of something, you want a set.

If arrays are ordered lists and if dictionaries are unordered lists with unique keys, what are sets? Good question. According to the Big Nerd Ranch Guide Swift Programming, a "set is an unordered collection of distinct instances."

What does that mean? That means that sets are like arrays in that sets have a single value. That means sets are like dictionaries in that they are both unordered lists. And like a dictionary whose keys must be unique, a set's values must be unique. In our post on dictionaries, we showed how multiple Rockies' outfielders could play left-field. In a set, though, one only Rockies outfielder can play left-field.

Why are sets important?
Sets are important when uniqueness is your highest priority because sets do the best job of sorting out unique items and keeping out duplicates.

When should I use sets?
So the big question is, when is a good time to use a set as opposed to an array or a dictionary? Another good question. Sets put a priority on uniqueness. In arrays, you can have multiple values that are the same (a team roster full of people named Javy). In dictionaries, you can also have multiple values that are the same (four left-fielders for the Rockies), but the keys must be unique (the names of the Rockies' left-fielders have to be different). With sets, uniqueness is paramount. It's kind of like retired numbers (yes, I know the Yankees have two 8s and two 42s, but play along). Let's look at the San Francisco Giants' retired numbers.





Alright, how'd we get here? First, created a variable, giantsRetiredNumbers. We then informed the computer that we would assign a Set of Integers (Set<Int>()) to giantsRetiredNumbers. Starting on line 6, we populated our set with integers that represent retired numbers from the San Francisco Giants. We've got Monte Irvin (20), Willie Mays (24), Juan Marichal (27), and Willie McCovey (44) among others.

What happens if the Giants hire a new clubhouse manager, a young kid who's never heard of McCovey, and tries to give old #44 to a September callup? Let's see:



We may have ordered #44 to be inserted into the giantsRetiredNumbers set a second time (line 16), but as we can see on the right side of line 16, there's still only one #44! Interesting that there is no error here, but maybe Xcode is getting chill about how it rejects stuff. One can hope.

What can I do with sets?
We can loop through sets like this:



For each retired number in the giantsRetiredNumbers set we printed each one which gives appears at the bottom of the playground console immediately above.

Sets also play nicely together. Remember Venn diagrams? NO?!? OK, here's one based on the old Simon & Garfunkle song.



Venn diagrams, like the one above, have two circles that represent distinct groups. In this case, the groups are "people who are breaking my heart" and "people who are shaking my confidence daily." The intersection of these two circles, that is, the one thing these two groups have in common, is Cecilia.

The union of these two circles is people who are breaking my heart AND people who are shaking my confidence daily.

Sets also have a method that checks whether or not there are duplicates between them. Let's walk through some examples of these.

First, let's check to see if Barry Bonds has his number retired with the Giants.



Just checking! No retired number for Bonds with the Giants. And that's how to check if there is a specific item in a set. First, we created a constant, barryBonds. Then we told the computer what set we wanted to check, the giantsRetiredNumber set. Then we ran the ".contains" method on the giantsRetiredNumbers set. We then had to pass an argument in the parentheses so the computer knew what value to check for, in this case, 25.

Let's say we wanted to create a super team of retired Giants and retired Pirates. What an outfield! Mays, Clemente, McCovey! (Stargell can play first). How would we do that? Let's take a look.



How'd we do that? First, we created our Pittsburgh Pirate super team, a set filled with the unique retired numbers of guys like Roberto Clemente, Willie Stargell, and Honus Wagner (line 17). Then we created a superTeam constant. To that superTeam constant, we told the computer to take the giantsRetiredNumbers set and to create a union with the piratesRetiredNumbers set.

Also notice that while the Giants had a 4, 11, 20, and a 42 like the Pirates, in the superTeam set there is only one 4, 11, 20, and one 42. Uniqueness: that's what sets do.

What if we want to see what retired numbers the Giants and Pirates have in common? How do we do that? Let's give it a go.



And the winners are 4, 11, 20, and 42 (line 19)! Let's walk through how we did that. First, we created a new constant, superTeamIntersect that we'll assign the numbers that the two teams have both retired. Then we picked one of the teams, in this case, piratesRetiredNumbers and asked the computer what numbers it and the giantsRetiredNumbers set have in common through the ".intersect" method.

Now what if you want to make sure that two sets do not have the same items in common? In this case, you are not looking for the exact items in common or not in common, just a "True, the two sets have nothing in common" or "False, the two sets do have something in common." Let's give it a shot.



False! And why is it false? Because as we learned in the intersect section above the two teams have both retired 4, 11, 20, and 42! So it is false that the two teams retired numbers are disjoint (in other words, it is true that they are not disjoint because they do in fact have four numbers in common).

Challenge:
Use sets to create a super team between the retired numbers of the Cubs and the Tigers. What is their union? Where do they intersect? Tweet me what you find (@randallmardus).

On Deck: Enums, Structures, and Classes!

Tuesday, September 6, 2016

The Rockies Outfield & the Dictionary Collection Type

Some things just go together: Adam Jones playing centerfield; Rickey Henderson leading off; The Philly Fanatic playing the fool. If there's one, there's the other.

And this is a good way to think about the second Swift collection type, the dictionary. As in a regular dictionary where you look up a word and you get its definition, in the dictionary collection type there are two parts: They are called the key and the value. The key is akin to the word in the dictionary you look and the value is akin to the definition of that word.  Together, the two are referred to key-value pairs.

In baseball, we find examples in players and the number they wear (Carlos Gonzalez: 5), players and the position they play (Adam Jones: centerfield), players and their place in the batting order (Gary Sanchez: third) to name just a few examples.



Why are dictionaries important?
They offer more advanced ways to store information. Rather than just storing one piece of info like arrays do, dictionaries store two pieces of information at a time.

When do we use dictionaries?
If you want to store all the members of a team, you want to use an array. If you want to store all the members of the team and the position they play, you want to use a dictionary. In other words, use a dictionary collection type if you need to store two pieces of information for each item rather than just one.

How are dictionaries different than arrays?
Arrays are arranged in an ordered list according to their index numbers. Because they are ordered, we can have multiple values of players named Martinez, Jackson, or Smith because they will be unique by index number. Because dictionaries are not ordered list, dictionary keys must be unique. Let's take a look at an example.



As we can see immediately above, we can put the Jackson family roster in one array, but we can't put the Jenkins family roster in one dictionary using the same keys, "Jenkins", each time. We get an error. Why? Because the computer can't differentiate between one Jenkins key and another. Rather, we have to do something like this:



Notice how the order of the keys on the right hand side is different from the order we entered them into the dictionary on the left (line 7)? Why is that? Because dictionaries are not ordered lists by index number, the order doesn't matter. All that matters are that the keys are unique.

Arrays and dictionaries are also different in the types of values they can hold. Arrays can only hold one data type at a time. If you start a String array, all they can hold are strings. But if you start a dictionary that has a String key, it can have an Integer value like this:



What can we do with dictionaries?
Good question. As with arrays, we can do a lot. Here are some examples, but there are many more that you can explore.

You can count the number of keys in a dictionary by using the count method.



You can find a value from a specific key. Let's ask the dictionary what position Carlos Gonzalez plays.



How did we do that? First, we created a new constant, gonzalezPosition (we could have created a variable). Then we called our dictionary, rockiesOutfielders, and told it what key we wanted a value for from the dictionary ["Gonzalez"]. And that's how we got the value, "RF", to the key "Gonzalez".

What if we want to modify a dictionary value? Let's say Gerardo Parra now plays right-field.



How'd we do that? First, we chose the dictionary we wanted to modify (rockiesOutfielders). Then we chose which key we wanted to change ("Parra") and then we created a new value for the key "Parra", in this case, his new position which is "RF". To make sure it worked we called the rockiesOutfielders variable. On the right hand side of line 9, we can see that Parra used to play "LF", but now plays "RF".

What if we want to add another outfielder to the Rockies outfield? Let's give it a shot. Say the Rockies are in a pinch and need to put backup catcher Tom Murphy in left-field.




Here we start with the dictionary, rockiesOutfielders, then we choose the new key we want to add to it ["Murphy"]. Then we create the value for the "Murphy" key: "LF". To make sure it added to the dictionary, we call the name of the variable, rockiesOutfielders, on line 8 and there's Murphy in left-field on line 8.

OK, the Rockies' manager has changed his mind about Murphy. Now we need to remove Murphy from the rockiesOutfielders dictionary.



This time we started with the dictionary's variable, rockiesOutfielders, then called the removeValueForKey method after the ".". The removeValueForKey method needs to know what key we are going to remove so we tell it by passing the "Murphy" argument in parentheses. When we go to the next line, Line 8, and call the rockiesOutfielders variable to check if Murphy is truly out of the outfield, we can see that he's either on the bench or behind the plate again and out of the outfield.

But see that nil on the right side of line 7? And notice how Murphy is completely gone from the dictionary? While the method may be called removeValueForKey, we didn't just remove the value, but both the key and the value. So, a bit of a misnomer of a method there to keep an eye on in the future.

At this point, I bet you're asking, "But can we loop through dictionaries?" Yes, we can. Check it out.



What did we do here? We split our key value pair (the player and his position) into two different string interpolations. On the bottom we can see all six keys from our rockiesOutfielders dictionary printed out as they complete the loop through the dictionary.

But what if you just want to loop through one part of the dictionary, not both? We can do that. Watch.



We did it thanks to another for loop. Let's walk through it. First, we used the "for" keyword to let the computer know we wanted to setup a for loop. Then we chose which part of the dictionary we wanted to loop through, in this case, the key. Next, we specified what dictionary we need to loop through (rockiesOutfielders) and called the .keys method to be even more specific about what part of the dictionary to loop through.

Now let's say we want to create a Rockies roster array. Well, we already have the outfielders in our dictionary. Can we just move them over to the array so we don't have to type everything all over again? We sure can. Here's how.



First, we set up a new constant that we will assign our new array to, in this case, rockiesRoster. Then we declared that rockiesRoster would be a Array. But what, exactly, will be in the array? Let's just include the keys from the rockiesOutfielders dictionary. And on the right side of line 7 we can see our new rockiesRoster array with just names, no positions.

Challenge: Recreate these exercises with your favorite teams and Tweet them to me (@randallmardus).

On Deck: The sets collection type.