Showing posts with label iOS programming. Show all posts
Showing posts with label iOS programming. Show all posts

Wednesday, February 1, 2017

The Wheelhouse Gets Rained Out

Hi all,

Last year I started writing The Wheelhouse, a blog that explained Swift iOS coding using baseball examples, metaphors, images, and videos. In that time I have learned a lot about iOS, Swift, and coding in general. I hope you have too.

Sadly, I am going to put The Wheelhouse on ice for now. Why? Because a look at the NYC job market shows 500 Swift openings and over 3,000 Python openings. So I’m changing my focus to Python.



That being said, I’m going to start a new Python project: I'm going to build a website that allows landlords to receive their rents online. I’m also going to write a companion e-book to the site so if you’re a landlord who wants to build such a site or if you’re new to coding and want to build a clone site, this is for you.

This project won’t have a baseball slant to it, but it will take you from soup to nuts and fill in as many of the gaps that novices usually fall into when working on their first projects with books or online tutorials. 


I hope you enjoy it, use it, and learn from it. Stay tuned. 

In Crash Davis We Trust,
Randall Mardus

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.

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!