Today, we'll go over another Swift data type, the Integer or Int.
What is an Int?
If a string is anything between two quotation marks, then an integer is any whole number (e.g., 2, 3, 19, 1002, -49275020457). In baseball terms, integers appear as wins, losses, home runs, hits, stolen bases, and saves to name a few instances.
Why are Ints important?
Declaring a variable (var ichiroUsHitTotal = 2974) or a constant (let ruth = 3) to have an integer data type gives the rest of your function or code a clear heads up that that variable or constant is an integer and as an integer can do certain things and cannot do other things.

For example, let cyYoungCareerWins = 511. In this case, Cy Young's career win total is 511 and because he's retired (and, well, deceased) that is a constant which means his career win total will never change. Because we know his career win total is an integer (511) we can now subtract from it another integer (316, his career loss total) to figure out how many games over. 500 he was for his career.

What can integers not do? As we learned in the post on strings, we cannot add strings and integers together. They're like oil and water, Earl Weaver and umpires, or Jon Lester and throwing over to first base.
When do we use Ints?
We use Ints when calculating things, either through addition, subtraction, multiplication, or division. The thing about integers is, we need to know in advance that the final answer will also be an Integer. Why? Good question. Say you wanted to calculate Cy Young's lifetime winning percentage:

Dude won 511 games. His lifetime winning percentage can't be 0! Of course not. It's 0.61789600967352. Unfortunately, 0.61789600967352 is not an integer. In terms of Swift, it's a Float and in this particular case because it is less than one, it is zero.
Here's another example to keep an eye out for. While Young had six seasons with a WHIP less than 1.000, let's take a look at his 1892 campaign with the Cleveland Indians when he had a WHIP of 1.062. Here it goes:

Again, because we're dealing with declared integers and the answer isn't an integer the computer doesn't budge. Instead, it comes out with the closest Integer, in this case one. On top of that, the computer rounds down. Even if Cy had walked 500 batters that year for an eye-watering 1.905 WHIP, the computer would tell you he had a WHIP of 1.000.
So what do we need to do to properly calculate things like WHIP, ERA, or OBP? We need Floats.
On deck: Calculating Clayton Kershaw's career WHIP with Floats.
No comments:
Post a Comment