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

Wednesday, January 11, 2017

Farm Systems, Darryl Philbin, and Swift Classes

Part of what makes the St. Louis Cardinals a special franchise is their farm system. St. Louis' farm system routinely produces starters and all-stars that make the Cards perennial contenders. Not too shabby for a small market team.

How do they do it?

The Cardinals establish a culture in St. Louis that they duplicate all the way down to Rookie ball in Johnson City, Tennessee. 

In our last post we discussed how we use structs to model data. We can also use classes to model data. But what are classes and when do you use classes instead of structs? Let's walk through those questions and, along the way, use baseball's minor league system as a coding example. 

What is a class?
Big Nerd Ranch's Swift Programming notes that like structs, "classes are used to model related data under a common type." 
And here's what classes do that structs cannot which Apple's Swift documentation points out:

  • Inheritance enables one class to inherit the characteristics of another.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • Deinitializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.
Let's flesh those out some more.

  • Inheritance enables one class to inherit the characteristics of another. This is particularly helpful if we want to create classes for baseball teams as each major league team has a number of minor league affiliates under them that are similar, but different. For instance, once we create a BronxYankees class with such properties as wins, losses, and attendance, the AAA ScrantonYankees can inherit all those properties from BronxYankees as they'll need them too, and then add a property that is unique to Scranton such as, DarrylPhilbinBobbleheadNights. We'll code out an example shortly.
When deciding whether to use a struct or a class, ask yourself if you think you'll need to use inheritance or not. If you are sure that you will not need inheritance, a struct is probably all that you need. If you know you'll need inheritance, create a class. If you are not sure if you'll need inheritance in the future because you can't tell the future and aren't sure how what you're building is going to change over time, choosing class over struct will do a better job of covering your butt and making your life easier for the long run.

Why?

Because if you choose struct now, but then realize down the road that you now need a class you will have to go back and change all your struct files and where they are called in your main file which is, technically speaking, a pain in the ass.

Now back to what classes offer that structs do not:

  • Type casting enables you to check and interpret the type of a class instance at runtime. Why is this important? For a few reasons. First, type casting allows you to check the type of an instance. Once you know what type an instance is, whether it is a String, Double, or a custom type, then you know whether it handles integers, floating numbers, strings or a custom type. Type casting also allows developers to know what protocols the instance conforms to according to its type. In other words, once you know what type something is you'll know what you can do with it. In baseball terms, if you are a hitter and you know what pitches the pitchers throws, you'll have a better at-bat. 

  • Deinitializers enable an instance of a class to free up any resources it has assigned. Specifically, deinitializers free up memory resources which means your program can run faster and more efficiently. A full description of deinitialization is available here in Apple's documentation with a working example included, but, in short, deinitializers remove set values from instances of the class you created when they are no longer needed. In baseball terms, initialization is like a player being given a uniform and number when he first joins the team and deinitialization is like when he hands in his uniform to the team before retiring. 

  • Reference counting allows more than one reference to a class instance. Earlier we created a BronxYankees class from which the ScrantonYankees inherited properties. In this case, ScrantonYankees are an instance of the BronxYankees class. Thanks to reference counting not only can ScrantonYankees inherit from BronxYankees, but so can all levels of the Yankees' minor system (TrentonYankees, TampaYankees, CharlestonYankees, StatenIslandYankees, etc). 
Now let's build out a new Xcode project that makes use of classes and inheritance.

Open Xcode and double-click on "Create a New Xcode Project". Choose macOS as your template and for this project choose "Command Line Tool" before clicking "Next". Give your project a name such as, YankeesSystem, and make sure that the language is set to Swift before hitting "Next". Then choose where you want to save your work. It can be in a specific folder, on your desktop, or wherever else you want; hit "Create".

Xcode will then open. On the far left panel click on the "main.swift" file which will open in the center panel with some sample code in it some of which we'll remove in a minute.

Create a new file (File > New > File) and name it BronxYankees. It will save under the main.swift file in the far left panel as BronxYankees.swift. Enter the BronxYankees.swift file by clicking on it.

Let's create our class and define what properties it will have.




For this project and this BronxYankees class, we'll start with attendance, wins, and losses and give them all initial values.

Next let's make them do something. Specifically, let's have them print out, "The Yankees have 72 wins, 40 losses, and a current attendance of 2000000."


First, we need to add a function to our BronxYankees.swift file. In this case, it is our seasonUpdate function that plugs in the wins, losses, and attendance values thanks to string interpolation.

To make this function run, we now go back to main.swift and call the seasonUpdate function.

On line 11 we call the file where the BronxYankees class resides and set it to a new variable called bronx. On line 12 we call the seasonUpdate function from the BronxYankees file. This returns:


which shows up in the console.

If we want to recreate the Yankees farm system we'll need to setup the Yankees' AAA affiliate in Scranton. Now let's create a subclass that inherits the wins, losses, and attendance properties that we created for the BronxYankees class. To do this we need to create a new Swift file. Let's call this new file ScrantonYankees. This is what that will look like:


On line 11 we create the ScrantonYankees class and we make it inherit from the BronxYankees class (ScrantonYankees: BronxYankees). By doing that we don't need to create another round of wins, losses, and attendance variables: the ScrantonYankees class automatically inherits them from the BronxYankees class.

But the Bronx is the Bronx and Scranton is Scranton. They may have wins, losses, and attendance in common, but they are not exactly the same.

On line 12 we show how Scranton is different: Scranton has Darryl Philbin bobblehead nights at their games (I'm just making this up).


But what happens if we call the ScrantonYankees seasonUpdate function? This prints out to the console:


This is nice, but it just prints out the BronxYankees wins/losses figures before printing the ScrantonYankees property we created. But what if Scranton actually has 38 wins and 22 losses? How do we change that?

It takes a few steps, but we can do it. Let's go.

First, go into the BronxYankees.swift file. After the seasonUpdate function we are going to add three new functions that allow us to change the values of our attendance, wins, and losses properties. They will look like this:



Let's walk through these. First, use the func keyword to create a new function. Then we give the function a name, in this case, we use changeWins, changeLosses, and changeAttendance - all names that indicate what the function is going to do, that is, change the values of our different properties.

We then pass an argument (amount: Int) that indicates that what we will pass will always be an integer type. Then we drop a { to announce that we are about to define our function.

Within our curly brackets we define our function. In this case, we are saying, "the number of wins/losses/attendance will change by the integer amount that we pass as an argument." 

When done with the function we close it up with a }. One big step done, two to go.

But, you say, why can't we just go back to the main.swift file, invoke changeWins and changeLosses, plug in our integer arguments and be done with it? Good question. Let's try that and see what happens.


On lines 12 and 13 we told our program to replace the BronxYankees' 72 wins and 40 losses with 38 wins and 22 losses for the ScrantonYankees. But as we can see in the console, the program added 72+38 and 40+22 instead, which is not what we wanted.

Fortunately, we can fix this by initializing our properties in the BronxYankees.swift file. Here's what that looks like:


By initializing our attendance, wins, and losses properties we make them ready for use. When we tried to use them before initialization we could not change the initial values we gave them. Now through initialization we can and we will. But first, some more explanation of what's going on between lines 16 and 19.

Line 16: We use the keyword "init" to announce that we are going to initialize our properties. We then pass attendance, wins, and losses as arguments and state that they are all going to be of the integer type. We then open up some curly brackets where we'll define our initialization function (lines 17-19).

"Self" in Swift is not an easy concept and can get meta pretty quickly so what I will say here is this: On lines 12-14 we have attendance, wins, and losses for the BronxYankees. On lines 17-19 we have attendance, wins, and losses for other, future instances of BronxYankees subclasses whether that is for the ScrantonYankees, the TampaYankees, etc.

To that end, lines 17-19 say, "the value of our attendance, wins, and losses properties will be equal to what we assign them in the arguments that we pass, not the initial values assigned to attendance, wins, and losses for the BronxYankees."

It is important to note that Swift initializers do not return a value as our example above shows. There are no values there. Rather, they serve to prepare instances of a type for use later on which is what we'll do next.

First, let's go back to our main.swift file. Once inside that we need to call on our ScrantonYankees subclass (line 11) and then call the seasonUpdate function (line 12).


Next we have to pass our attendance, wins, and losses arguments and their associated values to ScrantonYankees. While it's true that attendance has nothing to do with our final statement, we cannot run the program without giving attendance a value. As you can see in the console, it doesn't show up anyway.

So, as usual, a discussion on one topic, in this case classes, spilled over into other subjects as they all work together.

On Deck: The discussion on classes and structs continues in our next post which will go over the difference between reference types and value types, another important concept to understand when deciding how you want to build your programs.

Tuesday, January 3, 2017

Mookie Betts & the Swift Struct Type

If you're organizing a pickup game of softball on the Fourth of July, then getting all the details right isn't a big deal because the game is most likely a one time thing among a group of friends more interested in having fun. Chances are people are not keeping stats. Although there is always that one guy...

But what if you are organizing all of Major League Baseball, 30 teams that each play 162 games over the course of a regular season? That takes some organization. Organization of schedules, of travel, of players, of stats, etc. And it's not just for one year, but for an uncertain number of years to come.



How do we organize that data? In computing, we model that data. What's a model? Good question.

According to Wikipedia, "Data Model is an abstract model that organizes elements of data and standardizes how they relate to one another and to properties of the real world entities." For instance, a data model may specify that a data element representing a baseball team comprises a number of other elements which in turn represent the size of the roster, the size of the team budget, and the owner of the team to it.

To visualize this, I think of an Excel database. The name of our data model is the name of the database ("Baseball Team") and the names of the elements are the names of the columns and rows (roster size, team budget, team owner, etc). 


Once we have our data model setup, we can run through large quantities of data or values much faster than we could if we did each one individually without a model. That is, in earnest, a general overview of data modeling which can get more complicated.

Question is, depending on what you're organizing, how do you want to organize your data? As we've discussed in previous posts, there are different ways to organize information in Xcode and with Swift. Enumerations are one way, structures (aka structs) and classes are others. In this post we'll focus on what structs are, when to use them, and what they do.

What is a struct?
According to the Big Nerd Ranch's guide to Swift Programming, "A struct is a type that groups a set of related chunks of data together in memory. You use structs when you would like to group data together under a common type."

So let's break that down. 

We've seen types before, usually strings, integers, and doubles or floating point types. In this case, a struct is a custom type that you can create to fit your needs as you create and organize information. In our case, we're going to create a Hitter struct that keeps tract of the number of hits and homers that a players has. We will organize information according to these custom parameters.

Unlike previous posts that we have written and executed in Xcode Playgrounds, this time we will need to create an Xcode project to properly play with structs. Why can't we use structs in a Playground? 

The main reason we need to create a whole new project rather than use a playground is that we write structs in one file, typically an ancillary file, and then call those structs from another file, usually the main file, that our code exists in. Projects allow us to create and access multiple files: Playgrounds do not.

Why can't we just put them all in one file? If we did, when it came time for the computer to run our program it would run everything, not just what it needed that instant and this would take longer to run. By putting some important information in a separate file we keep our program faster, leaner, and more efficient.

When to use a struct?
We wouldn't need a struct to publish the fact that Didi Gregorious had 155 hits and 20 homers in 2016 because it's just one line that we can write out rather quickly ourselves. But what if we build a site that listed the names of all the players in baseball and how many hits and homers each hitter had? Considering that there are over 600 hitters in Major League Baseball every year, it would take a long time to write those all out. This is where structs and their data models come in.

What can structs do?

According to Apple's own documentation, structs can do the following:


  • Define properties to store values
  • Define methods to provide functionality
  • Define subscripts to provide access to their values using subscript syntax
  • Define initializers to set up their initial state
  • Be extended to expand their functionality beyond a default implementation
  • Conform to protocols to provide standard functionality of a certain kind
Sounds great, right? Now what does that all mean? Let's break those down because they will also be true of classes.

  • Define properties to store values: If you define a property such a hits, then you can give that property a value such as 200 hits. And once something has a value, you can use that value. If you don't define hits, then you can't give it a value and you can't use that value.

  • Define methods to provide functionality: Once you have your properties such as hits and homers, you can create a method, say, a method that calculates what percentage of a hitter's hits are homers, by defining a method that calculates that figure. This is what I meant in the previous paragraph when I said once a property has a value then you can use it. This is an example of us using that value to calculate something else.

  • Define subscripts to provide access to their values using subscript syntax: According to Apple's documentation, subscripts "are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval." 

  • For example, we can create an array called stewartWins that contains the total number of wins Dave Stewart had in some of his years as a starting pitcher and then access specific elements in the stewartWins Array by selecting an instance by choosing its appropriate index number. 


         
In this case, we want to see index number 3 which returns 22 wins so we write     stewartWins[3]. We can do the same thing with dictionaries as seen in the second example above.

  • Define initializers to set up their initial state: Can you imagine a hitter coming to bat without wearing a number on the back of his jersey? That's like variables or constants not being initialized with values. There are times when it's OK for variables and constants to not be initialized, but it's also nice to have the option to initialize them which structs support.

  • Be extended to expand their functionality beyond a default implementation: In other words, structs are not static or set in stone, but have the flexibility to expand their initial functionality. In baseball-ese that means you might come into the league knowing how to throw a fastball and curveball, but you can always pick up a change and a knuckle-curve: You aren't restricted to just what you had on day one.

  • Conform to protocols to provide standard functionality of a certain kind: While this is a little vague, it's another way of saying that structs, in general, play by standard protocol rules. In baseball-ese, structs will be around the strike zone - they won't kill anyone or your program.



An Example of a Baseball Struct
OK. So let's create a new Xcode project and our own struct.


Open Xcode and double-click on "Create a New Xcode Project". Choose macOS as your template and for this project choose "Command Line Tool" before clicking "Next". Give your project a name such as, hitterStruct, and make sure that the language is set to Swift before hitting "Next". Then choose where you want to save your work. It can be in a specific folder, on your desktop, or wherever else you want; hit "Create".

Xcode will then open. On the far left panel click on the "main.swift" file which will open in the center panel with some sample code in it some of which we'll remove in a minute.

Create a new file (File > New > File) and name it hitter. It will save under the main.swift file in the far left panel as hitter.swift. Enter the hitter.swift file by clicking on it.

Under "import Foundation" let's create our struct and define what properties it will have.

In this case, let's look at the career numbers, through the 2016 season, for Mookie Betts.



What do we have here? First, we created a struct with the struct keyword. We then gave our struct a name, in this case, Hitter which is capitalized. That's important. Then we open up a curly bracket to define our properties. The properties are all variables, one for the player's name (name), hits, and homers.

In this case, we've initialized our variables by giving them values ("Betts", 443, 54).

Now let's create a function so we can do something with our struct. Let's have ours say, "Betts has 443 hits and 54 homers."



Using the func keyword we create a new function which we call printHitterDescription. We add the () in case we want to pass an argument later. We'll leave it empty for now as we have no need to pass any arguments. And then we open up a set of curly brackets within which we'll write our function.

In this case, our function is an example of string interpolation, a quick way to show what structs can do. print() is a function within the printHitterDescription function that will print whatever we write in the parentheses to Xcode's console, below and to the right of the center section. Here, we want it to say, "Betts has 443 hits and 54 homers." We plug in our properties on line 17 (name, hits, homers) where we need them so the values will print out.

Now that the struct is ready to go, we need to connect the main.swift file to the hitter.swift file so it can pull the data it needs to complete the printHitterDescription function. We connect the two files by calling the hitter.swift file from the main.swift file. Here's what that looks like:



See line 11? That's where we call the Hitter struct from the hitter.swift file. In this case, we call it by setting Hitter() to the myHitter variable.

Line 12 prints out our "Betts has 443 hits and 54 homers" statement to the console by running our printHitterDescription() function on the variable myHitter that calls the Hitter file.

That's what it looks like to run a single instance through a model. In a future post we'll run more data through it so you can how that works.


Challenge: Create a new project with two Swift files one of which contains a struct for pitchers that models pitcher names, games started, and quality starts and then Tweet it to me at @randallmardus.

On Deck: Classes and how Structs and Classes are similar and different

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.