Still coding along…

joaquin

My last blog post was in March. I currently have 3 posts sitting in my drafts folder waiting to be revised and published. The nature of work and family, though, usually winds up pushing these posts back to a future, undetermined date.  Needless to say, I’m still coding along.

Much has happened since my last post on here. I took a new position in late June with Rheem Manufacturing working on their app, so my time at Emory (and my first real dev job) ended in mid June. I still look back on amazement at the amount I learned during this time from when I finished The Iron Yard. 21 month in a dev job just sort of demands it. Still, I was nearing the end of a project and ready for a new challenge. After several online interviews, a few phone interviews, and a couple face-to-face interviews, I accepted a position with Rheem. If you’re not already aware, Rheem manufactures air conditioners, furnaces, boilers, and probably most well-known for, water heaters.

Manufacturing is beginning to embrace the mobile space and our app, while consumer facing, is actually geared toward a different consumer–the contractor or plumber installing your a/c unit or water heater. It’s an interesting viewpoint and as Rheem has spent the time to immerse me in the different industries, it has given me time to think about how to help best serve the users of app, in an installation environment.

Part of my training was pair programming with the development firm, Stable|Kernel. They initially built the app and I was hired to assume future development. They’ve spent the better part of 3 year on it, so it was enjoyable to look at their development process, ask questions on how they attacked different requirements, and ultimately learn their approach to problem solving. Code reviews, both formal and informal, discussions of design patterns, explaining some of the more intricate parts of Xcode I had never really dove into before–all felt like my 21 months at Emory compressed into 12 weeks. One of the biggest takeaways, was that they switch back and forth between architectures as the requirements see fit.  While most of it uses MVC, there were some elements where they went with MVVM as the nature of the task made it more readable to me and anyone else that might look at the project in the future. I liked the flexibility. I was so stuck with trying to make my previous work fit into one architecture, I’m sure I actually made things worse. It’s nice to see a different viewpoint.

Now that my time with them has ended and the training wheels have been taken off, so to speak, I feel much more grounded in my abilities. Emory was a great jumping off point, Rheem is the next step in progressing. I look forward to the challenge.

On a side note, I may discontinue my  use of wordpress for my blog.  I’ve discovered Dev.to and I like their markdown capabilities more, especially as I write more on code.  When that first blog comes, I’ll link from here.  My queue of drafts on Codable, Interview musings, and Coordinators are still forthcoming…

Advertisements

Algorithms…necessary annoyance

Update: It was mentioned to me over the weekend that my title didn’t really tie into the content I presented (tip of the hat to Abbey Jackson!).  The original title of the post was supposed to discuss why I was continuing A&DS stuff even though I could spend that time learning new Apple APIs from the forthcoming Swift 4 release (the lab I work in does a ton of research using machine learning so I’d like to get a better understanding of how it works and it’s uses in app development).  The necessary annoyance part, to me, means that although I have a developer job, and I managed to get one without having to pass a rigorous A&DS interview, I do realize that potential future moves may require it and that I’m not particularly prepared for it. So rather than devote time to specific iOS-related stuff, I’m working on this instead. It’s interesting, but annoying too! 

A couple weeks ago, I hit the one year anniversary from when I graduate from The Iron Yard.  Since then, (after a couple months of interviewing) I’ve been employed by Emory University’s School of Medicine, seen The Iron Yard announce they’re shutting down, and generally just kept plugging away at learning all I can about Swift and app development.

There is always a general doubt that lingers when I attempt to teach myself new stuff.  Not having a background in CS, I occasionally have reminders about imposter syndrome (that voice that tells you that you aren’t really a developer, you’re faking it).  True, it’s stayed quiet for most of the last six months or so, but when I start learning something new and I’m not getting it, the voice gets a little louder.

When I was in interview mode last year, the common feedback I received after an interview was “your algorithms skills are really weak, you need to work on it.”  Algorithms and Data Structures (A&DS) is a course CS students take fairly early in their major. Bootcamps don’t look at it much.

Still, it’s a rite of passage that basically reminds me of the SATs in high school.  Colleges don’t really know how you are as a student compared with others, so there has to be some sort of fairly objective assessment that might indicate that you can indeed solve problems.  (* NOTE: this isn’t an endorsement of the SAT or ACT, and those scores aren’t an indicator of your success level in college and beyond, but, as imperfect as it is, a college having to decide among 10,000 candidates who may have a 4.0 in high school to fill 500 spots has to use something to distinguish the candidates and the test is the same across the country.)

Anyway, algorithm questions in interviews are just one of those things. I say this as a newer developer, as I have no idea what senior developer interviews are like.  When I was in the job search, a couple friends and I bought a subscription to a website that helps prepare for those type questions.  I used it for a couple weeks, but never made much effort at it (by then I had a job offer).

Fast forward to today and I’m looking over it again to see if some of those questions are easier for me now, than they were a year ago.  The short answer is: “not hardly”.  It’s a skill that must be worked at (at least for me). I’ve started working on one problem every two days during my lunch time to try and train myself to be better at these questions.  I’m in no hurry to change jobs as I really enjoy what I do, but I also don’t want to try and cram for stuff like this when the time does come for me to interview elsewhere.

And really, it doesn’t hurt to know this stuff anyway, regardless of whether I’ll ever be asked questions like this in the future.

So my first problem to solve was this:

Given a list of stock prices over the course of one day, write a function that would calculate the maximum profit you obtain from buying one share of the stocks.

So basically I have an array (list if you’re using Python) of stock prices.

let stockPricesYesterday = [10, 7, 5, 8, 11, 9]

The rules are:

  1. Buy one share and sell later (no shorting the stock)
  2. Account for if the stock price contained any negative numbers (or if all were negative, what’s the best “loss” you have.

Clearly look ing at the 6 prices, it’s easy to see that we need to buy when the price is $5 and sell when it’s $11.  But what if the array contained a price for every minute the market was open?  The function should work regardless of the size of the input.

So, looking at this and knowing the answer, I still had no clue how to get started.  I’ll use the array, look at each element and decide when to buy and when to sell.  Aside from that, I wasn’t really sure how to do this without the need to use multiple loops. (Big O notation is not something I’ll talk about at the moment, but basically it’s a measure of how long an algorithm takes to solve something…the shorter the better)

I’ll be the first to admit, that I had to use the website’s help on this.  I didn’t look at the solution, but I did have to keep choosing the “I need a hint” button.  Eventually I got to a point where I feel like I could get started.  These are the hints I was given.

  1. Maximum profit is the goal. We calculate it by selling at the current price.  It’s the difference between the current price and the lowest price we’ve seen so far.
  2. If the difference between the two (Current Price – Minimum Price) is larger than the current maximum profit that we’re keeping track of, then update the currentMaxProfit to the new profit.

So I have to keep track of several things. The minimumPrice I’ve seen, the maximumProfit I’ve seen thus far, the currentPrice I’m looking at and the currentProfit margin while I’m at the currentPrice.

The website mentioned an idea of using a “greedy” approach to solving this.  The greedy approach is basically keeping a running total of the end result (max profit) while I search through the list of numbers, and updating it along the way if I find a larger max profit.  (more information about greedy algorithms can be found here: Greedy Algorithm Basics

Once I had all this information (hints), I was ready to start writing a function.  I want the function to be able to take an array of prices, process each price and determine if the current price I’m looking at minus the lowest price I’ve seen thus far gives me a better profit than the currently held maximum profit. If the current price I’m looking at is lower than the minimum price, then I need to update that as well.

All my life I’ve never been one to make lists, or to outline. If a paper needed writing, I’d just start typing and edit on the fly.  This isn’t the best approach.  I must have re-written this function quite a few times as I made several mistakes.  As I look back on the answer, an outline might have been helpful.

  1. Find the minimum price (basically the first price in the array to start)
  2. Find the maximum profit (basically the difference between the first two prices in the array to start)
  3. Now, look at each price individually (i.e. Iterate through the array/list)
    1. find the current price (that is the price a that particular iteration array[0] is the first price, array[1] is the second price, etc…)
    2. find the current profit (difference between current price and the minimum price we originally set)
    3. Compare the current profit to our already found max profit.  If current profit is larger, then update max profit to be the current profit
    4. Compare the current price to minimum price set earlier.  If the current prices is lower, update the minimum price to be the current price
  4. Move on to the next price in the list and repeat

Strangely, once the blueprint (outline) is listed, the problem doesn’t seem to be that terrible.  However, my biggest problem was not being able to visualize what variables I’d need to keep track of.  I go back and forth on this.  Sometimes I just jump in and start adding a bunch of variables that I think I’ll need and delete the ones I don’t use.  Other times, I try to add as I go.  Neither way has proven to be very useful.  They’re both hit or miss.

I guess that’s why I need to practice.  Anyway, my final function wound up looking like this:

Screen Shot 2017-08-25 at 9.34.46 AM

Note: stock_prices_yesterday was a global property I declared earlier in the code…it’s just not visible.  I probably should update it to stocks[1] - stocks[0] instead.

This was question 1 of the website.  It took me about a 1/2 hour to work through. I’m trying to keep in mind that I haven’t done this in a while and I’m just getting my brain used to thinking this way.  Algorithms aren’t like riding a bike…yet.

Of course, I might go the rest of my career without every being asked to do this. But problem solving is a skill in constant need of refinement, and despite my outward appearance, I don’t want my brain to be rough around the edges!

Adjusting the sails…

Most have heard the quote that I reference in my title.  I remember hearing it at my high school graduation. It’s pithy, memorable, but for a long time, to me, utterly useless.  I had no context to apply it.

That all changed on Memorial Day last month.  For those unfamiliar, the last Monday in May is Memorial Day, a time where we honor the memories of soldiers fallen to defend the United States. For most, it’s a long holiday spent at the lake or a cookout. For others it is remembering loved ones that paid the ultimate sacrifice.

For the past month, I’ve taken a more pro-active role learning delegates and protocols in swift.  Most documentation or how-to videos involved protocols with extension, which provide a default implementation on how to use the protocol.  It’s much harder to find a good tutorial to pass some data from one file to another via a delegate.  I’ve tried to find good examples that help to answer my questions instead of bringing up more.  Much of what I’ve found hasn’t been helpful.  For a couple of weeks, this kept me pretty much at a standstill.

Fast forward to Memorial Day.  It’s a CrossFit tradition to perform the Hero WOD “Murph” on Memorial Day. Michael Murphy was a Navy SEAL who sacrificed himself to get a radio message to help his fellow SEALs.  Part of his story is told in the book & movie “Lone Survivor”.  Murph’s favorite workout when he couldn’t get to a box was a 1 mile run, 100 pull-ups, 200 pushups, 300 air squats, and then finish with a 1 mile run…all while wearing a 20 lb. weight vest.

The-Murph

So I participated in Murph for the first time over Memorial Day. There is nothing glamorous about it, at least from my perspective.  It’s a way to honor his memory as well as others who have fallen to defend the United States.  There is very little fanfare.  We show up, we workout, mostly in silence, and then we encourage others who are still trying to complete the workout.

I’ve been battling shoulder issues for the past few months and was recently allowed to resume so activities that involve the shoulders.  However, I was really worried about the pushups in Murph.  I decided to scale them so as not to face the wrath of physical therapist and endure more therapy (aka torture) at her hands.  So I did pushups from my knees rather than the standard.  At around 120 reps, my shoulders started complaining.  What to do?  End my workout, disappointed in myself and feeling like my contribution towards Murph’s memory didn’t count?   I came really close to calling it.  However, in the midst of the heat, humidity, and mild discomfort (yes, that’s sarcasm), the whole quote about adjusting the sails popped up.  I think there is something spiritual about trying to stretch your physical capabilities.  In this case, I had a moment of clarity.  An “a-ha!” moment.   Rather than just stop the workout, just change what you’re doing.  So I went to sit-ups for the rest of my pushups requirement.   Sure, it’s not the prescribed “Murph” (not that I was anyway as I wasn’t wearing the weight vest), but it’s still a way to honor his workout, and not give up.

So at the hour and twenty minute mark, I finished my final 1 mile run and completed my first Murph.  Of all the accomplishment I’ve had, this wasn’t bound in glory, a sense of accomplishment or any sort of fanfare.  Instead, I felt grateful.  I had the privilege of completing Murph.

The following Tuesday at work, sore from the previous day, I decided to change my approach to learning how to use a delegate pattern with protocols.  Instead of reading and searching for tutorials, I searched for code.  Any sort of delegate paired with a protocol.  How did they use it?  What triggers the delegate?  How do I assign it to View Controller that I need to perform the action.  I stopped waiting to have someone explain it to me, and instead went and found what someone did, and try to explain it to myself.

The end result is that I gained a small foothold in how delegates work.  I’m no expert.  But I was able to accomplish what I wanted, learn to adjust during my learning process, and once again, use a lesson learned in CrossFit in my career.  It never ceases to amaze how I can learn career lessons from a non-career related part of my life.

 

 

Leveling up

My lab consists of four developers, all bootcamp graduates. We have 2 iOS developers, and 2 Android developers. The Android developers are converted from other disciplines, so they have some experience in other areas besides Android. Both are very good back-end developers, having built back-end systems for the lab in both Ruby on Rails and Golang.

My supervisor has suggested I do the same so in the little spare time I have, I’m venturing into Golang and Dart to learn more about back-end and front-end development. That rabbit trail has led me into systems programming, which has historically been done in C. On top of that, I’m still playing with Algorithms and Data Structures so that I can be prepared for the eventual job interviews after my time at Emory in concluded.

Make no mistake. I’m not a front-end guy. I’m not really a back-end guy. But the pragmatist in me understands the appeal to a candidate that is more well-rounded. I’m not trying to leave iOS or Swift. I’m just trying to make sure I have an understanding of how the other stuff works in conjunction with iOS.

It can be overwhelming. Do I look at several things or focus on just one and get really good at it? I tend to go back and forth. “This week I only want to focus on A&DS” or “This week I’m going to spend the first 30 minutes of work on A&DS and then my lunch break on Dart.” It’s not particularly well-organized, I admit. Still, I’m feeling my way around and trying to find what works best for me. Organization has never been a strong suit of mine.

Podcast ranting

I listen to a few Swift podcasts while driving to/from work. Most of these are quite good. A few months ago, I thought I’d found a promising one. It was supposed to be geared toward new developers and the topics were one’s I was (still am) currently learning.

I was please with the first few from this one particular podcast, but around the time of the inauguration, it turned to more of a ranting/preaching podcast on what the podcaster deemed as not fair/ or “here’s how it should be.” Initially I defaulted to his judgment because, here I was, a brand new developer, and his first few podcasts were helpful and informative. Over time, I discovered he had 1 week more experience as a developer than I did. Not that being new at development is wrong. I’ve learned some good things from him. But once he began preaching about how new developers should or should not do this/that/the other, I began to wonder why he thinks he’s experienced enough to make these kind of opinions. Most developers I talk to on Slack are constantly having to adapt to an ever changing industry. His advice runs counter to that logic. It reminded me of the pointless faculty meetings I sat in on as a teacher and were told “Do it this way.” Why? I have a better way. I have a circumstance that doesn’t make your “way” the best way. Why should I adopt it/limit myself?

I reached out to him to ask if he was planning to go back to discussing iOS dev because lately I didn’t get much out of his podcast. He said he was, so we’ll see. I say all that to say if someone with 30 years experience talks about how much she’s changed in the industry and had to adapt, why does someone with 8 months experience feel like he’s got it all figured out? I don’t like limitations. I feel it stifles problem solving and makes my job boring.

Algorithms

I’ve started working through a book called How to Solve it by Computer by R.G Dromey. It was written in 1982. It was recommended to me on the iOS Developer Slack forum as a good starter book for bootcamp grads that need to level up on Algorithms logic. It’s a great read. The programming language he uses is Pascal, but aside from that he walks through the steps on how to solve basic problems. So far I’ve worked through how to reverse a number, how to convert a decimal number to any other base system (octal, binary, ternary, etc…) and how to calculate the factorial of any number. It’s enjoyable without being overwhelming, which I what I got when trying to solve problems out of Cracking the Code or Interviewcake.com.

Functional Programming

My previous posts on closures has led me down this rabbit hole called functional programming. I briefly touched on FP in those posts without explicitly calling it that. But as I read through a book on test-driven development (writing tests to make sure functions work the way they’re supposed to), the author is trying to move away from what he calls “writing swift in an objective-c way”…aka…the way I currently understand…

For example:

return string.characters.reduce(0) { $0 + (vowels.contains($1) ? 1 : 0) }

This is the Swift-y way of writing what is basically a for-loop and an if statement.

What I think it’s saying is this: take all the characters in a string and starting with a value of 0, reduce all the values of an input I give into one single value. Basically, this is starting with 0 and if conditions are met, we will increase that value. At the end of the function(closure), we’ll have our final value.

Ok…so what exactly are we combining/reducing/evaluating? Well, we’re reducing the characters in a string, but the closure part of the expression above specifies what will be reduced. In this case, comparing the characters of the string to some vowels. If this character matches with any of the vowels, increase the value that we started with (0), by 1. Otherwise, if the character does not match with any of the vowels, increase the value by 0.

I have left a few things out to reduce for simplicity. I could have expanded on what $0 or $1 mean, but I haven’t come up with a good explanation yet. It makes sense in my head, but I haven’t figured out the best way to put it in writing. Perhaps the next blog post will cover that.

Closures – continued…

As I’m reading more about using closures in Swift, and then reflecting back upon the closures I’ve used, it leads me to more questions. Down the rabbit hole I venture!

Below is a closure I wrote last week. In fact, it’s exactly what has led me down this rabbit hole. I got tired of failing my way through finding a solution with no discernible reason as to why it worked. I was lost in Swift-land with no roadmap, no compass, and no sherpa to guide me through. I still found my way home, but if asked to repeat the performance, I knew I wouldn’t be able to.

UIView.animate(withDuration: 0.75, delay: 0, options: .curveLinear, animations: {self.cursorLabel.frame.origin.x = nextAnswerX }, completion: nil)

So what I was trying to do was get a label to move across the screen as the user answers each question. This animation is part of a function I wrote that will move the cursor if the user answers the question or chooses to move to another question using the left and right arrow buttons that I also have on the screen.

So, what is going on here? The animate function is pretty clear. I want to animate something. It takes several parameters such as the duration of the animation, if I want the animation to delay before it starts, the style of animation I want (in my case I’m using curveLinear), and then the last two parameters are called animations and completion.

Those two parameters take a closure. The completion closure I have set to nil because I don’t want anything to happen after the animation has finished. The animations closure, though, I have used.

animations : {self.cursorLabel.frame.origin.x = nextAnswerX }

As wordy as that looks, I’m grabbing the x-value position of my cursor label (where it currently sits) and setting it equal to the x-value position of where I want it to be. The nextAnswerX is a reference to another label’s frame.origin.x value as I don’t want to alter it’s state. I want a copy of it. I actually made that mistake in the first part of the closure, but in the opposite way. I made an instance of the x value of the cursor and was trying to alter the instance instead of the actual cursor. It’s similar to writing a letter, photocopying it, altering the photocopy and expecting the original to have changed as well. Sometimes we want the state of the original to change, and sometimes we want to leave it alone.

Now the odd part is that this animation closure doesn’t use words like return or in anywhere in there. Doing some research, I’ve found, courtesy of the Apple Swift documents:

Animations : A block object containing the changes to commit to the views. This is where you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be NULL.

So, it looks like since the block takes no parameters or return value…which looks like this:

(String) -> String
or
(String, String) -> Int

We can eliminate that part of the closure syntax when deciding what the view should be doing. My code is finding the frame that houses the label, then finding the x value of that frame, then setting the x value to a new value.

To be honest, that may be the simplest closure I’ve ever written. I was curious how they set up a closure that doesn’t take parameters and this is what I’ve found.

animations: @escaping () -> Void

So the animations parameters is an escaping closure that takes a function that returns no value (that’s the -> Void part). Upon further research, the -> Void part is required even though the closure doesn’t return any sort of value. If the closure just had the (), Swift would think it was empty tuple.

The escaping part means the closure will be called after the method has returned. By that, it means “Hey we might need to use this closure later, so lets hang on it.” This could be because the closure is running on a background thread, or waiting for the user to interact with the screen, or some other reason I haven’t yet discovered. My animation only happens upon a button click, and after looking online, apparently happens after the function is called, so it has to be escaping. I’ll admit, I don’t understand that fully right now.

Update: I saw this in the Apple documentation about closures…

One way that a closure can escape is by being stored in a variable that is defined outside the function.

So if I have a variable holding a closure, and I place that variable into a function that accepts the closure, that function will need to be set up to have an escaping closure so I can access the variable later after the function has been called. I don’t think that’s technically what is going on in my situation as I’ve just written out what I want my closure to do inside the animation parameter, but it is the first time that I’ve seen documentation that makes sense to me on when to use the @escaping syntax.

I’ve now gotten to the point where the information I’ve read is a repeat of other information, so I don’t have anything new to add, but suffice to say I’ll be paying more attention to completion handlers and other parameters that require closures to get a better idea of why some have to be escaping and others do not.

As far as the syntax goes, I understand better what is happening, and the short-hand syntax doesn’t unnerve me as much when I see it. I just need to keep writing them the way I’m comfortable until the shorthand becomes second nature. For now, I’m all about code readability.

#fiyf

Closures – my interpretation

I’m going to try and explain to myself how closures work.  This is a normal departure from my usual blog posts as it will be more code focused–which was the original point of my creating this blog.  So my goal is to twice a week, blog about a specific programming topic I’m trying to learn or use, or would like to use in my programming.

So a closure is a function–without a function name.  I write functions all the time.  They’re easy to understand as the function name generally describes what it does.  For example:

func double(input : Int) -> Int {
        return input * 2
    }

This function takes any sort of integer and sends back a value of that integer multiplied by two.

Now, I can use that function as a standalone by calling it…


  double(8)

and it will return a value 16

What if I want to use that function as a parameter or argument in another piece of code?  What if, for example, I want to take a number and divide or multiply by 4 or add 16 to it?  I could write those individual functions similar to the one above, or I could write one function that allows me to customize what I want to happen to the input on the fly.

If that’s confusing, it certainly has been for me.  I’ve used closures and never really understood them.  The code I used was almost always written by someone else and I trusted it worked.  But as I write them more and more, I have this desire to understand why it works.

So I want a function that I can reuse and that I can alter what happens to the input (for example, an integer) at any time.   Basically,  I want my function to accept a number from the user, and then manipulate that number in any customizable way I want; basically, i want to take that integer, modify it, and return that modified integer to be used elsewhere in the function, and return another value.

func modify(input : Int, byApplying f : (Int) -> Int) -> Int {} 

So the stub of the function I have above (which I borrowed from ‘A Swift Kickstarter’), takes a number from the user which I have named input.  byApplying is a placeholder name that Swift 3 has now incorporated to allow the user to understand the context of the argument.  byApplying is basically a nickname for what follows after it — in my case f (shorthand notation for me, the programmer to indicate a function) of the following data type (everything after the colon).

(Int) ->  Int 

In my instance, my function needs to take an integer type and will return an integer type.  Once that argument has performed whatever I need it to do, it will take that answer, and return at the end of the modify function, which is denoted by the return f(input) below.

The first time I saw this, I was confused.  Wait a minute…I’m returning a parameter from the function?  Short answer is yes.  I’m taking the second parameter of the modify function, putting the first parameter into it and returning the value.

So if we look at the original double function from above, we could do something like this…

modify(3, byApplying double) 

So what is happening, is double is taking the first parameter, 3 , and using it inside of it’s function.  It then returns the answer.  Since double is supposed to take an integer and multiply it by 2, it’ll return the value of  6 .

So, for most people, that would work fine…if all you needed to do was multiply by 2..and there are certainly easier ways to accomplish that.  But what if you needed to customize that double function on the fly?  You still want to take an integer and return an integer, but the math involved may change depending on what you need.

You could write other functions and pass it into the byApplying parameter…for example:

func addSeven(input : Int) -> Int {
    return input + 7
} 

and then call the addSeven function in the modify function…

modify(14, byApplying : addSeven)

and it would return the value of 21.

Or you could write the logic of addSeven or double or divideOneHundred directly into the modify function.  Basically customize it as you see fit.

This is where a closure comes in.  it’s basically a function without the function name.  Instead of naming it, you just wrap what you want the function to do inside  of curly braces { }. You also write it where the second parameter of the modify function should go.

modify(14, byApplying: { (input : Int) -> Int in return input + 7 } )

So what is happening here?  Well, the addSeven function took one argument, input, and returns an Int.  The closure above does the same thing, hence the (input : Int) -> Int part in the first half of the closure.  It matches exactly with the argument and return value in the addSeven function.

The ‘in’ part of the closure is what separates the expression in the first half of the closure with the body in the second half.  Basically, the closure reads: “input is an Integer which returns an integer and I’ll use input’s value IN the following bit of code….which in our case is take the input value and add seven to it and return (send back) that value.

Now, that finally made sense to me once I started using closures more, but it was never intuitive.  I had to use the closure, trust it worked, and then the more I used it, the better I became at figuring out how to ask the question on why it worked–a backwards process to be sure, but sometimes code is like that.  It also didn’t help that most of the closures I saw first looked like this…

modify(14) { input in input + 7 } 

or

modify(14) {$0 + 7} 

tumblr_m5wdv30ps91qb7gbyo1_500
They mean the exact same thing as my earlier closure.  They do the same thing.  They just look different.

So this…   

modify(14, byApplying: { (input : Int) -> Int in returninput + 7 } ) 

is using the two arguments in the original modify function, input & byApplying.  However, in Swift (and probably other languages), if you’re last parameter is a closure, you can just delete the byApplying part, close the parenthesis after the input part and write your closure after it…this is called a trailing closure.

becomes this:  

modify(14) { (input : Int) -> Int in return input + 7 }  

but we can take it a step further.  Since Swift can infer (understand) the data type you are using, in this case an Int that returns an Int, the code…

now becomes this:  

modify(14) { input in return input + 7 } 

Basically, it knows that the input parameter is an Integer.  It also knows the closure returns an Integer so we just lop that bit of extra code off.

If the closure only contains one expression, like ours does..i.e. input, we can also lop of the return part…

now becomes this:  

modify(14) {input in input + 7} 

The $0 part is new to me and I have yet to come up with a good explanation or demo, but it basically just means that $0 is the first parameter in the closure (i.e. input) and lop off the ‘in’ so it becomes:

modify(14) {$0 + 7 } 

So for me, who is just now getting the hang of it, I will probably stick with this

modify(14, byApplying: { (input : Int) -> Int in return input + 7 } ) 

or this

modify(14) { (input : Int) -> Int in return input + 7 }  

because the extra bit of code helps explain to me what is happening.  As I get used to closures, and begin writing my own, then I’ll start using more short-hand syntax.

It’s like any other language you learn.  Slang is picked up after you already understand the language.  I’m going to hold on using the swift slang until I feel I can converse normally in it.

If you don’t understand closures, I understand you pain.  I don’t really understand them either, but I want to understand them, so it does provide me with some motivation to learn them.

Recharging

#fiyf

I’ve been at my new job for 8 weeks.  I have a great time learning topics I’ve never dealt with before and although it’s slow going sometimes, I have yet to doubt myself on whether I’ll solve the problem, nor have I doubted that I’m in the right career.  Stress, anxiety, joy, repeat–the emotions of a coder.  I mean, who gets up in the  middle of the night to go to work to try out a solution to a problem that’s been plaguing them for days?  This guy.

That said, I could tell I was getting run down the last week or so as I skipped CrossFit completely for the week.  This week marks my one year anniversary of when I walked into CrossFit Loganville, so taking a week off in week 51 of 52 is probably not going to hurt me too much.

I also had trouble getting going in the morning once I go to work and just felt worn down.  I’ve probably been running at breakneck speed this entire time and my body said, “SLOW DOWN!”.

So what’s the best way to recharge?  Spend time with fellow coders!

I flew out to Salt Lake City last Thursday to visit the current Iron Yard cohorts, see some of the people in my cohort and teach a kids coding class. I wanted to share some of the encounters I had after I graduate and was searching for a job.  I also wanted to share how I coped with what felt like endless rejection.  But basically, I just wanted to be around fellow people who understand the fraternity that is a bootcamp.  Almost all of us are career changers, a bit older, looking to become the newbie in a competitive industry.

Getting to listen to their projects, answer their questions and basically, finally have a proper Iron Pints was just the pick me up I needed to come back and spend more time deep in my learning environment.  Perhaps boot campers are an anomaly, but we are definitely social creatures.

I don’t know how often I can afford to recharge that way, but I do know that 2-3 times a year is going to be my goal.  I left to head out there hoping to help a few soon to be graduates, but spending time with them helped me too.

img_0019
Downtown SLC during Christmas