Learning is enjoyable sometimes…

A few weeks ago, I signed up to take an Algorithm and Data Structures course on Coursera. Part of my reason for this is that I like having stuff explained to me, but mostly because the course has deadlines and I find it easier to stay motivated if the threat of a “0” is looming.  The coursework can be completed in any language but they have starter files and tests already set up for C, C++, Java, & Python.  We’re welcome to use other languages, but we’d have to write our own tests.  Fortunately for me, my first language was Python so I’m dusting off those skills to complete the coursework.

I’m in week 4 of 5 in course 1 of six-course series.  While I don’t know if I’ll complete all six, I have gained some pretty nice insight into how to tackle problems.  Greedy strategies, divide-and-conquer, among others are explored and the course requires us to think about the time-limits required when we submit our assignments.  The correctness of the assignment is not only “can you write an algorithm to complete the task, but  also “can you keep the algorithm from going over the time limit?”  No brute-force/naive answers allowed!

Getting back into Python has been entertaining. Initially I had to write out my algorithm in Swift using Xcode’s playground, and then translate it into Python.  After a couple of weeks I’ve been able to transition into just using Python.  I still write it in Swift afterwards just to compare the syntax differences of the two, but it’s nice to be able to pick something back up after not using it for almost two years.

So what problems have I solved? We started with Fibonacci, which I’ve done before but this was the first time I spent really exploring how it is computed recursively vs. iteratively. Even if not optimal from a memory allocation standpoint (most of the time), recursive functions are really beautiful in their simplicity of code. It reminds me of a more elegant while-loop. Initially I begin to wonder why even learn to use recursive functions if they suck memory so quickly when dealing with large numbers, until we got to the Greatest Common Divisor (GCD) problem.

Note: Recursion in programming is a function that continues to call itself until some terminating condition is met.  I write the function and call the function in the same code. For example:

someFunction(parameter A, parameter B) -> Value {
// do some stuff
return someFunction(parameterA, parameterB)

Screen Shot 2017-09-22 at 9.23.00 AM

GCD is is comparing 2 (or more numbers) and finding a divisor that both numbers share. For example:

gcd(6,8) -> 2

2 is largest number that six and eight can both be dividing by. 3 works for 6, but not 8, 4 works for 8 and not six; you get the idea.

But what if the numbers are really large? say 2,877,988 and 956,432 ?

can you imagine write a loop that starts at 1 and divides all the way up to those numbers checking to see if both have remainders of 0 when being divided? How long that must take?!

Well the course let us know a secret about large numbers. The remainder taken when dividing the first number by the second number has the same GCD as the original two numbers.

Screen Shot 2017-09-22 at 9.23.52 AM
I didn’t really understand this until I saw it in action. (See below) Also, how did people figure this stuff out?!

So even though the number is smaller, the GCD is still the same.  So basically, to find the GCD of the original numbers, keep dividing the first number by the second number until the remainder is 0.  Once you have that, the first number left is your GCD.

Here is a better visual of “trick”:

Screen Shot 2017-09-22 at 9.29.38 AM.png
This made much more sense to me than the Lemma above.

I have two numbers, A: 3,918,848 and B: 653,264. I divide 3,918,848 by 1,653264 and the remainder is 612,320, which we will call A-prime.  I replace the A with B, and put A-prime in B’s old place and perform the same operation again.  I keep doing so until A-prime is 0.

In this case, recursion actually doesn’t take terribly long as it’s reducing the size of the number pretty quickly, unlike when building numbers up during a Fibonacci sequence (1, 1, 3, 5, 8, 13, 21…).  So an efficient way to find the GCD of two numbers actually is to use recursion, though probably not the only efficient way…

Here is the Python function:

Screen Shot 2017-09-22 at 10.00.43 AM

It amazes me how short it is.

Using that algorithm allowed me to complete another assignment that finds the Least Common Multiple.  I won’t go into it but they provided another tip on how to calculate LCM using GCD and again, it provides a short elegant solution.

I think the decision to take this course, for me, was the correct one.  I’m being exposed to some handy tools, I’m obligated to finish assignments since it is costing me a monthly fee and the assignment are providing a nice warmup to my day for me while I drink my first cup of coffee.  (Note: if I haven’t finished the problem after 10-15 minutes, I wait until my lunch break to finish).

This week we began looking at binary and linear search algorithms.  In the past, when I would look at these, I just tried to memorize it so I could regurgitate it if it came up in an interview. Now, I have a list of questions I ask myself and can look at mathematical explanations and make sense of them, which aids in my understanding all the more.

None of what I’m doing may ever be needed, but I’ve finally gotten to the point where I view learning algorithms as not a means to an end in a job search…which is where I was a year ago.  Instead, it has become “I really want to learn this stuff. I find it interesting.” Perhaps at some point I’ll even do it without having to spend money to motivate myself!


Tripped up on closures…again!

I’ve posted before about learning closures. Earlier this year, I was really making an effort to understand how they work. My examples, though, were contrived, or rehashes of other peoples’ examples. As such, my ability to remember them suffers. Context is so crucial to understanding something. I was working on a problem at work today where I need to sort an array of data.  For some reason, I kept blanking on how to do it.  I could write the code that does it, but I couldn’t explain it to myself.  Here was my problem…

var meetings : [Meeting] = [
Meeting(startTime: 0, endTime: 1), Meeting(startTime: 8, endTime: 11),
Meeting(startTime: 2, endTime: 8), Meeting(startTime: 10, endTime: 12),
Meeting(startTime: 9, endTime: 10)]

I wanted to sort the array by startTime. Had this been just an array of numbers, I could have sorted it pretty quickly. For some reason, though, having instances of a Meeting class was throwing me off. I knew that this code would give me what I needed:

let sortedArray = (meetings.sorted { $0.startTime < $1.startTime }) 

This is really shorthand syntax. I know it works, but I could not explain to myself. So I tried the long hand way. Unfortunately, when I tried to write it in a way that made sense to me, I kept getting errors from the Swift Playground page I was working in. Undaunted, I went looking for answers. The Apple documents offer this when working with closures:

{ (parameters) -> (return type) in (statements) }

Hmmm…okay, the parameters I want to pass in, I thought, were the startTime of the meetings. So I wrote something like this.

let sortedArray = meetings.sorted(by:
 { (s1,e2), (s2, e2) -> Bool 
in return s1 < s2 }

What I thought I need to pass into the closure were the start times and end times and sort it that way. I was way off.

As it turns out, when I create a new array like I did with sortedArray, if I declare the type of Array it is, in my case [Meeting], that is the parameter that is passed into the closure, not the properties within the Meeting instance. I didn’t discover this until I explicitly typed it out, and used my old friend, Option-click, which told me what type sortedArray was. When I began typing in the sorted function on the meetings array, Xcode offered this little gem:

Screen Shot 2017-08-28 at 8.02.04 PM

As it turns out, I’m not passing in meeting.startTime or meeting.endTime into the closure. I’m passing the entire Meeting instance. In fact, the closure, as seen in the screenshot, takes two meetings from the array and compares them to return a Boolean value. What it evaluated is everything after in. Once I have the meetings passed in, I can access any of it’s properties to do my comparison.

Screen Shot 2017-08-28 at 8.12.52 PM

What I didn’t understand before is that m1 and m2 are just parameter names for the objects I’m passing in. They represent the meeting instance, not the properties contained within the meeting…which is what I really wanted to evaluate.

So in the end, in order to explain something to myself, my code wound up looking like this:

let sorting : [Meeting] = meetings.sorted(by: 
 { (m1, m2) -> Bool 
in return m1.startTime < m2.startTime}

Yes, it’s not very “Swifty” and in the future, I can use the shorthand trailing closure syntax and be able to look at it and know exactly what is going on. However, using code and being able to explain what the code is doing is a better indication of understanding than blindly trusting something I find on the internet, see that it works, but have no idea why.

I realize this topic is pretty junior for many developers, but it further reinforces what I discovered when taking calculus in college. If you don’t use something often, you forget it. Code is no different. It also helps when learning something, you have a problem you are trying to solve rather than seeing someone else’s example and saying “Yeah, that makes sense.” I do not expect this to be my last post on closures. Especially since I still have more functional programming to learn!

On the upside, at least as I see it in my growth as a developer, I went to Apple documentation rather than Googling for an answer in StackOverflow. As tempting as it was to ask my fellow iOS Slack channel mates, I decided to see if I could figure it out first. When time isn’t urgent, it’s amazing how much patience I have when solving a problem!

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!

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.


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.

I’m still here…somewhere.

I suppose my attempt at twice weekly blog posts was a bit ambitious. I’ve been rather busy at work trying to finish up the second game on our project and while I have explored the topics I’m interested in: enums, functional programming, protocols, and still more on closures, I’ve yet to have time to write about it.

Last week began the annual CrossFit Games competition. The Open is available to anyone who wants to attempt it and serves as the qualifying stage for Regionals, and eventually the Games itself. If you’ve read my blog in the past, you’ll know how important CrossFit has been for me in both physical and mental improvement, so it’s an exciting few weeks for me.

The Open consists of 5 workouts, one per week that are announced on Thursday evening. Participants have until the following Monday, 8pm EST, to complete the workout and upload their score, verified by a coach.

I completed 17.1 at Friday Night Lights at CrossFit Loganville. Last year, I had to scale every workout as I was new to CrossFit and couldn’t handle most of the movements required. This year, I was able to attempt the prescribed (Rx) workout. Big steps for me!

If that wasn’t enough, I attempted it again on Monday too see if I could do better which turned into 5 more reps that I had Friday night. The physical and mental gains are always encouraging for me. It rejuvenates my desire to improve, both at CrossFit as well as at work.

So in the spirit of that rejuvenation, I will double down on my efforts to blog more regularly. Certainly the twice a week goal is too ambitious, but I think twice a month is an acceptable and attainable goal.

The next topic will be Protocols and Protocol-Oriented Programming in Swift, as I used them in a Weather app I built, but didn’t really quite get them. So I’ll explain what it’s doing so as to clarify to myself how they work.


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
(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.


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…


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 } 


modify(14) {$0 + 7} 

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.