Wednesday, May 25, 2016

Cal Ripken, Jr. & Constants

When baseball fans think of Cal Ripken, Jr. they think of consistency: A man whose name we saw in the lineup for 2,632 straight games, a record streak that spanned 16 seasons. Ripken was a constant in the lineup because his presence there did not change.



And that is what a constant in Swift is: Something that does not change. Constants are established by the keyword "let". Here's an example in an Xcode Playground:



If we even tried to change a constant, we'd throw an error. Go ahead, try to run this below the "let battingThird = "Ripken"" line:

let battingThird = "Murray"



No dice. As his manager assigned Ripken to bat third everyday, so we assigned Ripken to the constant "battingThird".

It is important to note that we do not equate Ripken with battingThird. The equals sign here is not the equals sign we are used to from elementary school math problems. More accurately, we are assigning the value to the right of the assignment operator (the = sign) to the constant on the left of the assignment operator (=). We are assigning Ripken to battingThird just the way a manager assigns a player to a position or a spot in the order.

So, as you can imagine, it's better to read statements that include = from right to left. If "let battingThird = Ripken" walked to the plate, old Yankee public address announcer Bob Sheppard would announce it as, "Now batting, Ripken is assigned to the constant battingThird. battingThird." This is about as intuitive as "When you come to the fork in the road, take it," but there it is.

Why are constants important?
Constants are important because they nail down a value and keep it consistent. Once you know Ripken is batting third, you don't have to think about who is batting third anymore and you can depend on that constant to not change. You can also concentrate on the rest of the lineup which is full of question marks, or, variables.



When do we use constants?
Developers use constants for parts of their code they do not expect to change ever. Examples of this include someone's date of birth, Social Security Number, eye color, and Mariano Rivera's run in from the bullpen music.

On Deck: Jose Oquendo and Variables.


No comments:

Post a Comment