When I played third base as kid I knew I didn't have enough time to think once I got the ball, so I did my thinking in advance with a running dialogue in my head between pitches.
"If they hit a grounder to me, I'm going to first. Else, I'm covering the bag.
"If they hit it to left field, I'm the cutoff home. Else, I'm covering the bag.
"If they don't like my 12 year old mustache, they can kiss my butt. Else, cool."
In other words, I went through different possible conditions that could occur and came up with how I would respond to each condition.
We do the same thing in Swift programming. If you click on Baseball-Reference.com's black login button...
...then a login pop-up appears so you can enter their username and password; else, the you stay on your current page.
If you select this Oscar Gamble cross-stitch...

then Etsy will put it in your shopping cart; else, nothing happens.
These either/or, if/else decisions are called conditionals.
Let's recreate in code the conditionals from this scene in Bull Durham:

Why are conditionals important?
Conditionals allow users of apps and websites to make decisions whether they are playing a game and deciding to swing at a pitch (if I tap a button, swing...)/take a ball (else, do not swing), or order that Oscar Gamble cross-stitch.
When do I use a conditional?
Use a conditional when you have at least two possible conditions and outcomes. A good way to know if you need to use a conditional is if you can complete this thought, "If (insert what might happen), then (insert the result of that condition; else (insert another possible condition), then (insert the result of that second condition)." If you can do that, then you have a conditional. Else, not so much. See what I did there? Ha.
Side note: See that "" next to crashQuote? What is that? It's an empty string. Why is it empty? Because, in this case, there are two possible outcomes depending on what happens. If I fill in that string from the start, because it is a variable (see the var?) it will just change anyway depending on the outcome so I may as well leave it empty and let the appropriate outcome fill it in later.
Challenge 1: Pick another scene from Bull Durham where Nuke doesn't listen to Crash, code it out, and tweet it to me (@randallmardus).
Challenge 2: Pick a scene from Major League, code out a conditional, and tweet it to me (@randallmardus).
On Deck: Comparison operators!
No comments:
Post a Comment