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.

Thursday, September 1, 2016

Baby Bombers & the Array Collection Type

In the next few posts we'll go over three different ways to organize information that you can then pull from when you need it. This post will run a little longer than usual so feel free to come back to it. First, we'll start with the array collection type.

What is an array and why is it important?
To quote from Apple's Swift documentation, "An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions." Translation: An array will store all strings, all integers, or all floats, but will not store a mix of strings, integers, or floats. What's an ordered list? That means that Swift assigns an order to the string, integer, or float values you have in your array. The first string in an array is 0, the second string is 1. What? That doesn't make sense? No problem. I'll post an example below in a minute. What else should you know about arrays? Arrays can have the same value more than once. If you make an array of a team's roster by surname and you have more than one Martinez, Smith, or Jackson, the array can handle it. How does the array tell them apart? Through the unique index numbers assigned to each Martinez, Smith, or Jackson. OK. That's a good start. Let's jump into an example. 



Say you wanted to create an array collection type to keep track of all the new Baby Bombers that the Yankees have called up this year. We'll start by creating an array, informing the computer that we will fill the array with strings, and then set that array to a variable called babyBombers.



See those [ ] brackets? Those brackets indicate that our babyBomber variable is going to be an array. Now let's fill or initialize that array with the name of a Baby Bomber.



There! We've added Gary Sanchez to the array. But what about Aaron Judge, Tyler Austin, Ben Heller, Ronald Torreyes, Luis Cessa, and Chad Green? Let's add them to the babyBomber array.



How'd we do that? We took three steps. First, we dropped a "." after the name of our array. This is like Sanchez putting his hand down to call a pitch. Want to see what other kinds of pitches you can call with that "."? After the last line above, type babyBombers. and take a gander at just some of your options:



What you see there is just a fraction of the functions you can call after that "." If you scroll down within that box you'll see many more. For now, we'll focus on the append function.

After the "." we typed append. And lastly, we told append exactly what to add to our babyBomber array by passing an argument. In our cases, the arguments are the names of the players. We pass arguments with ( ) parentheses immediately after the function keyword append.



You can see here, highlighted in blue, that Xcode shows us the append function and how if we do choose to append, that we'll need to include a new string element such as "Sanchez", "Judge", or the name of another Baby Bomber if we want to add it to our babyBomber array.

What if we want to remove Tyler Austin from the array? How would we do that? Let's give it a shot.



And Austin's gone! But how'd we do that? First, on line 14, we called the removeAtIndex function which, like the append function, takes an argument (). But wait, why can't we just pass "Austin" as the argument? Good question. Here's what that would look like:



In other words, we can't pass "Austin" as the argument to remove Austin because the removeAtIndex function only takes an integer or Int. But how do we know what Int Austin is? Another good question.

To answer that we need to think of the entire array as an index. In the back of some books you may find an index. That index is a complete list of all the topics addressed in the book.



While a book's index is arranged alphabetically, an array's index is arranged numerically starting with zero (0). In this case, "Sanchez" is 0, "Judge" is 1, and "Austin" is 2. So when we pass 2 as our removeAtIndex argument that's how we tell the array to remove Austin.

As you may have noticed when you typed "babyBomber. " into line 14 of your playground and saw all the different function options you had, there are a lot. I'll go over a few particularly popular ones here, but I highly recommend playing with the rest to find out what they do. I've found one of the best ways to learn is to just try things out to see what they do.

What if, say, you had the entire Yankee farm system in your array and you wanted to know how many players total you had. How would we do that? Well, we'd call the count function.



In this case, there are seven players in our babyBomber array. What if you want to add a little extra information to one of your Baby Bombers in the array? Say, you want to add "Jr." to Austin (he's not a junior, work with me).



How did we do that? First, we chose the array (babyBombers) then we chose where in the array we wanted to add something, in this case [2], and then, because our array is a variable full of strings, we told it exactly what we wanted to add. In this case, we want to add a comma immediately after Austin, then a space followed by Jr. And what about that +=? What's going on there? That's a little short hand. The long hand is, "babyBombers[2] = babyBombers[2] + ",  Jr." In other words, we are changing the value of babyBombers[2] by adding ", Jr." to "Austin".

What if we want to replace one of the names with another name and keep it in the same spot in the index? For example, let's replace Tyler Austin with Derek Jeter's unborn son, Jeter, Jr.



Like last time, we chose the array we wanted to edit, babyBombers, we chose which value in the array we want to edit [2], and then we assigned a new string value to that array, "Jeter, Jr."

What if we want to add an array of Yankee September call-ups to our babyBomber array? Let's take a look at that.



How'd we do that? First, we created a new array, septemberCallups, and filled it with strings such as, "Young, Jr.", "Mitchell", and "Severino". Then we set that array to the variable septemberCallups. Next we setup a for loop that goes through the septemberCallups array for each string value, or in our case, each of the three callups, and then appends it to the end of the babyBomber array which we can on the right of line 19.

We've appended new array items to the end of the array, but what if we want to insert a new item to the array in a specific place? Let's try that by inserting "Severino" after "Judge".



Before we complete this, take a look above at what Xcode offers us after we type ".insert". Xcode asks us for two things: to enter our new element which is a string ("Severino") and an integer to identify where in the array it should go. Now let's finish inserting Severino.



And there's Luis Severino on the right hand side of line 14 right after Aaron Judge and before Tyler Austin.

Now let's say you're working with a friend on a project and the goal of that project is to create a master array of everyone who has ever played for the Yankees. Your friend has amassed a big list that she's put into an array and so have you. Now you want to see if the two lists are the same. If they are, there's a chance you've got everyone. If not, you'll have to iron out who is missing whom. How do we check to see if the two arrays are equal? Let's take a look.



For the sake of time, we'll assume small lists of Yankees, one for Bob's list of Bombers and one for Jill's list of Bombers. A quick eye-test concludes that they both have all the same players, but Xcode tells us that the two arrays are not equal. Why?

Remember how arrays are ordered lists, in other words, that their orders matter? Well, Bob and Jill may have the same players, but they are listed in different orders so according to Xcode they are not equal. Bob and Jill will have to try another collection type to solve their problem.

Challenge: Re-write these examples with your team's rookies and Tweet them to me (@randallmardus).

On Deck: The dictionary collection type.