Preventing Burnout during a Global Pandemic

A benefit of graduating and then entering the workforce right in the midst of COVID-19 is that the transition to working remotely from home was a lot easier. I had been taking my classes at home for my last 1.5 semesters, so I was used to the discipline required to stay motivated and productive in a non-office setting. There are some changes engendered by this pandemic that will persist for many years, however, and I think that some that graduated when I did will rarely, if ever, work in a traditional office, at least for the next ten years or so. For those that are in my position — transitioning from remote learning to remote programming, we are actually in a much better place to succeed and contribute to our companies because we never had to acclimate to being in an office, having in-person meetings, water-cooler conversations, etc. Still, it’s possible for everyone to experience burnout regardless of their coding background and experience, and the isolation of the work-from-home environment can definitely contribute to it. As a precursor to what I do to prevent it, I should say that no matter what your mental health needs to be put above anything else; those that are dealing with these issues need to prioritize them and take the time to relax, decompress, and do whatever it is that you love. My boss is very on top of these things, and wants me working only 30 hours a week, but if yours isn’t please take advantage of the flexibility afforded by working from home and take an hour or two a day and do whatever it is that brings you happiness.

Your work environment

I remember when I moved out of my parents home and into a small apartment with my girlfriend, my setup was just a desk and a laptop. I would normally start the day there, in my extremely uncomfortable desk chair, get sick of it, and migrate over to the couch. Well, if I was sitting on the couch, I might as well turn the TV on for some background noises. And, if it’s Jeopardy, I’ll be learning things too, so I’m still being productive. Working from home brings with it new and absurd ways to justify putting yourself in unproductive environments, and these excuses happen more and more often when you don’t put effort into your work environment. When my girlfriend spilt a glass of white wine on my keyboard, that was the final straw. My typing speed fell down to around 10 WPM, and I was driving myself crazy. Your work environment doesn’t need to be expensive — mine is definitely middle of the pack, with a 27′ monitor, a Ducky keyboard (would recommend, although my LEDs were unnecessary), and a Logitech gaming mouse. For those without the means to do it, whether it be freelancers, hobbyists, or startup developers taking equity in lieu of pay, you can realistically buy yourself all of these things for $200, maybe less. Psychologically, when I invested in my own productivity, it paid its own dividends. Since I spent $500 on this setup, I might as well use it.

Set a timer

When I begin my day I set a timer for two hours, and then I take a half-hour break. I repeat this process until I’m done with my work, or it gets to be the end of the day. This provides structure for me to do my job, similar to an office setting. Staying disciplined and adhering to the schedule is hard, but you’ll find it’s rewarding once you get to the end of the day, and the half hour breaks are long enough that you can go take a walk, take a nap, play a video game, read a book, without questioning whether or not it’s worth the trouble.

Set extracurricular goals for yourself

As fun as programming can be, even developers have things they like more than programming. Everyone has hobbies, but during the pandemic my leisures, social, physical, or otherwise, largely regressed from my everyday life. Setting goals for these leisures helped me stick to them and improve at them, which offers a sense of fulfillment and wholeness different from succeeding at your job, and just as important. For me, I wanted to get back into shape after spending a year and half in complete inertia. Walking sounded like the right thing to start with, so I try to get 10,000 steps every single day. I’m not perfect at it, but achieving that goal is a way for me to hang another hat on the day. I also go to my local gym and play basketball for around 45 minutes in the morning, just to get a good sweat in once a day, and at the end I shoot 25 3 pointers and see how many I can make. You’d be surprised how something as little as making 19 out of 25 3 pointers can invigorate you for the rest of the day. I guess what I’m trying to say is that having a diverse set of interests and activities that you can set goals for will help you in your work as well. Motivation is a holistic concept — finding it anywhere will help you with everything you devote your efforts to.

As a last resort, reset your computer

If you are really feeling burnt out and unmotivated, reset your computer. I know it sounds weird, but there’s something oddly cleansing about starting from scratch. Make sure all of the files and projects you care about are backed up, wipe the hard drive, reinstall the operating system, and experience the satisfaction of seeing nothing on your Desktop, Downloads, Applications, etc. For me, it’s like a got a brand new computer. Now, don’t be doing this every week, because the time required to reinstall some of your applications, like XCode, for example, will make it not worth your time, but if you are really feeling on the edge of burning out, there’s something very calming and relaxing about getting your computer back to where it was before. Recloning all your repositories, logging into all your important accounts, reconfiguring your favorite IDE, are all things that you can just check off your to-do list without thinking much.

These are the things that I do to prevent me from burnout. If anyone else has any other tools they use to stay motivated, please sound off in the comments! This is by no means an exhaustive list, and I’d love to see what everyone else thinks.

FDS: Integration with fuikit (pt 3)

Hello again! Today I’m going to be writing again about FlexDataSource, this time integrating another library in LithoByte’s arsenal of tools, fuikit (functional UIKit). If you’d like more background on that library, I’ll refer you to another blog post here. I’d summarize fuikit as a way to tap into the functions of boilerplate UIKit classes outside of scope. Especially in the case of UIViewControllers, this is useful for a variety of reasons, one being that you can abstract styling and configuring your tableViews and collectionViews to outside of the UIViewController. The ideal that I strive for as a developer is to just have my ViewControllers as a container for local variables, outlets, and actions, where all computation and logic that happens therein occurs outside of the actual ViewController. Let’s take a look at a simplified version of FPUIViewController:

Here, we override the viewDidLoad method in the View Controller, call its superclass’ viewDidLoad, and then call an optional function called onViewDidLoad on itself. The things I mentioned above can all happen outside of this FUIViewController, and what we did in the last blog post will become a lot cleaner doing so. Similar to last time, we still use our FlexModelItem to store our configuring function, and have a function that returns our network call.

Now, let’s define our new UsersViewController which will now inherit from the FUIViewController we defined above.

That’s it. That’s our View Controller. Four lines, doable in two with weird formatting. Now, let’s define a function that’ll take in a function called styleVC, that will take in a UsersViewController and return Void, and return the UsersViewController we create.

The static function makeFromXIB is from a library called PlaygroundVCHelpers, which provides useful helper functions to instantiate your View Controllers. Now let’s make a function called dataSource that will take in a network call and return a publisher of a FlexDataSource.

Just like last time, we use the modelItem function to create another function that will map Users to FlexDataSourceItems, and then map the resulting array of items to a FlexDataSourceSection the section into an array of that section, then that section array to a FlexDataSource.

Finally, let’s make a configureVC function that takes a UsersViewController and a CombineNetCall, uses our dataSource function to generate the publisher, sinks into said publisher, and finally sets it to our UITableView‘s dataSource property.

Note that setting the tableView property of our FlexDataSource will in turn set the dataSource property of that tableView.

Now we have all the tools in place to create what we had at the end of my last post, but now our UsersViewController is only four lines of code. We just need to fill in our usersViewController function:

That’s it! I think it’s important to note that complex code is complex, and sometimes it’s inevitable that your UIViewController will be hundreds of lines of code. Being an iOS consultant/developer, you spend a lot of time thinking about the intersection between what’s repeatable in Swift and what can be automated. You’ll find that abstracting out this intersection will result in less lines of code 90% of the time, but will scale better 100% of the time. Now when you want to add a new feature in your UserTableViewCell, you know exactly how to do it (add the outlet in your class, then add to your configureCell function). When you want to add a new feature in your UsersViewController, you just tap into its onViewDidLoad. You know this function will have access to all of your VC’s outlets, because you know exactly when it is called. There have been many times where I try to initialize a UIViewController and access its outlets, only for my app to crash because the view hadn’t loaded yet. You can keep your auxiliary functions in different files or folders, and you can achieve better test coverage using more free-functions vs. executing your logic in your ViewControllers. FlexDataSource, FunNet, and fuikit are the three pods that I use most, and they are just as useful by themselves as they are with each other.

FDS: FlexModelItems and FunNet (pt 2)

In the last blog post, I took a deep-dive into the basics of FlexDataSource, an extremely useful tool to quickly configure a relationship between models and UITableViewCells, and a relationship between an array of models and a functioning UITableView. As a quick sidebar, I just want to note that FlexDataSource also works with UICollectionViews much in the same way that I’ve explained in the last post. Although I’ve explained why FlexDataSource is useful, I’ve yet to show why it’s flexible with regards to an arbitrary model to be displayed. That is where the FlexModelItem class comes into play. Here it is:

FlexModelItem is generic with two parameters:

  • T: The model we want to populate the cell with (no restrictions)
  • C: The cell we want to be populated (must inherit from UITableViewCell)

FlexModelItem inherits from FlexDataSourceItem, so we know that we can plug in a FlexModelItem whenever a FlexDataSourceItem is used and not lose any functionality. FlexModelItem takes a model and a configurer in its constructor. The configurer is a function that will populate whatever cell type C is with respect to your model of type T. This obviates the need to define your own subclasses of FlexDataSourceItem every time that you have a model-to-cell relationship. The FlexDataSourceItem protocol isn’t generic, however, and FlexDataSource uses the configureCell: (UITableViewCell) -> Void function to populate the cell and a certain indexPath, so we niftily use the *-> operator, defined here, that essentially fixes the first parameter of a two parameter function and returns a function that only depends on the second parameter. In this case, we fix model: T to our configurer: (T, C) -> Void and set the resulting function (C) -> Void to our local variable to save. Then, in our overridden configureCell function, we optionally cast our UITableViewCell to C, and call our configurer on that cell.

Now, as an example, let’s say we have a network call that is supposed to return an array of Users, each with a firstName, lastName, and occupation. We also have a subclass of UITableViewCell called UserTableViewCell that has a nameLabel and an occupationLabel. Now, we want to display a UITableView of all the users that get returned from our network call.

We first define our UsersViewController below:

In our viewDidLoad, we have to set up our dataSource. We have also declared an indicatingCall that we need to store in our UsersViewController so it doesn’t get deallocated. For those who want to read about the network layer that I normally use, please do so here, but for all intents and purposes, a CombineNetCall holds all the data you need for a network call:

  • The URL
  • HTTP Method
  • HTTP Headers
  • URL Parameters
  • HTTP Body

A CombineNetCall also has a fire method that essentially makes a URLSessionDataTask and resumes it as you would using Swift’s native network layer. It also has publishers for the HTTPURLResponse, Error, and Data that you would tap into in the callback of URLSessionDataTask.

Our next step is to create our network call. Elsewhere in our project we define usersIndexNetCall:

What we’ve done here is set up a network call to GET https://example.com/api/v1/users, and we stub our network call with an array of users defined below:

Now, let’s define a function in our ViewController called setUpNetCall that takes in a CombineNetCall and returns an AnyPublisher<FlexDataSource, Never>:

This function stores the call, and taps into the call’s $data publisher and uses a function called modelPublisher that will automatically decode the data publisher’s value into the value-type of the variable, in this case, [User]. Next we use the -*> operator (similar to *->, just with the second parameter instead of the first) and the constructor of FlexModelItem to create a function that maps a User to a FlexModelItem. Then, we use the free-function version of map, and the modelPub‘s map method to create a publisher of [FlexDataSourceItem], and use build-in methods from FDS to create a FlexDataSource publisher, which we return.

Lastly, all we need to do now is get our network call, create the FlexDataSource publisher, sink into it and set it to our dataSource variable, which will then trigger it’s didSet and set itself as our tableView‘s dataSource and reload the tableView.

There — we did it! If you’re following along in this tutorial, you’ll notice that your UIViewController only has one method defined inside of it, besides viewDidLoad. And the cool thing is — no matter how complicated your models become, displaying a list of them is exactly the same process. All of the meat of your programming work goes into the configuring functions that populate your cell’s with your model. Building a UIViewController that makes a call to your backend, decodes it into your model, saves the models, and displays them in a UITableView, with regular, out of the box, Swift would take much longer and require much more lines of code. I’ve gone a long time without conforming a UIViewController to UITableViewDataSource, and this is why. In my next post we’ll build off of this and integrate fuikit, another library I use everyday, so you can see why my UIViewControllers never conform to UITableViewDelegate either.

Happy Coding!

FDS: Abstraction of UITableViewDataSource

UITableView’s are a tremendously important part of UIKit that, as any self-taught iOS developer can attest to, is included and emphasized in pretty much every online course. For good reason too — you’d be hard-pressed to find any app out there on the app store that doesn’t list some type of object relevant to the user. Because of how ubiquitous Tables are, I’m sure most people reading this blog post will be familiar with the following paradigm:

Suppose we want to display a list of users. Our users only have a name, and we want to use our UserTableViewCell that has a nameLabel. We define ViewController below.

class ViewController: UIViewController {
  var users: [User]?
  @IBOutlet var tableView: UITableView!

  override func viewDidLoad() {
    // set delegates, datasource to self
    getUsers()
  }

  func getUsers() {
    // get users somehow, set to users
  }
}

We get our users in viewDidLoad, and then at some point after that we reload our tableView.

Next we extend our ViewController to implement UITableViewDataSource and UITableViewDelegate.

extension ViewController: UITableViewDataSource,    
                             UITableViewDelegate {

  override func tableView(_ tableView: UITableView,  
                          cellForRowAt indexPath: IndexPath) 
                               -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(
                       withIdentifier: "myIdentifier") 
                       as? UserTableViewCell else { 
        return UITableViewCell() 
    }
    cell.nameLabel.text = users[indexPath.row].name
    return cell
  }

}

Since I started learning iOS Development, I have probably had to do this process 100 times, yet had never thought to look at the processes herein that are repeated over and over again:

  • Either registering my cell as a nib or giving it an identifier in my storyboard
  • Dequeueing your cell from the tableView
  • Doing some type of styling and populating of the cell based on what model I’m listing

If you look at the code above, you’ll see that only one line (the one where we set the cell’s nameLabel isn’t generalizable.

Which brings us to FlexDataSource, a publicly available CocoaPod that takes care of the repeatable code above. Let’s take a look at the underlying ADTs within this module.

FlexDataSourceItem

A FlexDataSourceItem has three functions — one that returns the cell identifier, one that returns the cell class, and one that configures the cell. Keep in mind, however, that this is a protocol, and at first glance it may be hard to see where the variability in the objects to be listed lies, but subsequent implementations of this protocol will account for this.

FlexDataSourceSection

The FlexDataSourceSection is pretty simple, and acts only as a holder for an array of FlexDataSourceItems. You can view this as analogous to keeping a 2D array of models, one array for each section of the tableView.

FlexDataSourceProtocol

FlexDataSourceProtocol specifies a tableView and an array of FlexDataSourceSection‘s. The protocol also has an extension below with some helper functions, but hopefully you can see how we get from this infrastructure, holding on to the tableView and sections, to a tableView on the phone’s screen displaying sections of data. Here is the extension:

We can see now how the data for each FlexDataSourceItem is used:

  1. Get the name of the cell’s class
  2. If there is a nib file matching that cell’s class, register it with the tableView
  3. If not, register the cell’s class with the tableView under the identifier returned by the required method.

We can also see how the tableView configures each cell:

  1. Make sure that indexPath leads to a stored FlexDataSourceItem
  2. Dequeue the cell from the tableView (if registerCells has already run, this will always work
  3. Configure the cell using the FlexDataSourceItem specified by the indexPath

Now, say we want to make a tableView that has 3 sections: one of all blue cells, one of all red cells, one of all green cells. The normal UITableViewDataSource methods would be complicated, switching on the section of the given indexPath and setting the background color depending on it. With FDS, we can do it the following way:

And then we can make the same ones for blue and green. Then we can construct a FlexDataSourceSection comprised of as many RedItems we want in the section, and do the same for BlueItems and GreenItems, construct a FlexDataSource from that, and assign our UIViewController‘s tableView to it in its viewDidLoad. There is no pesky extension where you have to do the same thing every single time, and the only classes you’re interacting with are the ones that control what cell you are displaying and how you want to configure that cell. It’s not initially obvious how much time that saves you, because switching on a section number and setting the background color is a pretty simple example. In Part 2, we will look at a useful child class of FlexDataSourceItem and integrate it with FunNet — a networking library that I have talked about here.

FunNet: A fully modular Network Layer

At LithoByte, most of my work is spent developing tools that are widely applicable and used across most, if not all, apps. The time spent on these tools pay their dividends when we use them in client work, or in the development of other tools. One thing that most apps will have is some type of network layer that moderates the communication between front end and backend, as well as handling errors that may occur in a diagnosable way. A couple of years ago, when I was coding both the front end and backend of a passion project, I didn’t see much use in a generalizable network layer — I would just store the server URL in the environment, and append whatever URL path string I needed, and then take the raw JSON as a [String: Any?] and use that to display what I needed to on the front end. It was a pain, but I didn’t know any other way to do it.

Working for LithoByte, however, I’ve been very comfortable with a library called FunNet (https://github.com/LithoByte/funnet) which makes networking so much easier, as I’ll explain to you shortly. FunNet is usable across all iOS versions post-10.0, and post-13.0 uses the Combine Framework to achieve the asynchronous nature of networking.

Whichever iOS version you are working with, however, Elliot Schrock has done a great job of starting with a strong foundation and building off of it. Thinking about a network layer, what changes and what doesn’t? The URL will change, but the base URL string will mostly stay the same. You will probably need to do different things to the response, the data, and the optional error depending on the data you expect to come back, but the fact that you need to tap into those types are constant.

Without further ado, let’s take a look at the first class that encapsulates everything about the actual URL string except for the path: ServerConfiguration:

open class ServerConfiguration: ServerConfigurationProtocol {
    public let shouldStub: Bool
    public let scheme: String
    public let host: String
    public let apiBaseRoute: String?
    public var urlConfiguration: URLSessionConfiguration

    public init(shouldStub: Bool = false, scheme: String = "https", host: String, apiRoute: String?, urlConfiguration: URLSessionConfiguration = URLSessionConfiguration.default) {
        self.shouldStub = shouldStub
        self.scheme = scheme
        self.host = host
        self.apiBaseRoute = apiRoute
        self.urlConfiguration = urlConfiguration
    }
}

As you can see, it really serves only as a wrapper for the different components of a URL scheme, and providing smart defaults so the only information you really need to supply are the host and an optional apiRoute (e.g. ‘api/v1’). Now for the counterpart of the ServerConfiguration, called the Endpoint:

public struct Endpoint: EndpointProtocol {
    public var httpMethod: String = "GET"
    public var httpHeaders: [String: String] = [:]
    public var path: String = ""
    public var getParams: [String: Any] = [:]
    public var timeout: TimeInterval = 60
    public var postData: Data?
    public var dataStream: InputStream?
    
    public init() {}
}

Here we have all the things that can or will change about the actual URL: method, path, parameters, postData (analogous to request body), etc. It shouldn’t be difficult to see that Endpoint and Server Configuration, when paired together, have all the information necessary to fire off any JSON-encoded URLSession. These two classes serve as the base for our networking layer, but we still need to abstract one more layer to enable the user to “tap in” to anything we might get in a URLSessionDataTask callback. We need a NetworkResponder to do this:

public protocol NetworkResponderProtocol {
    var taskHandler: (URLSessionDataTask?) -> Void { get set }
    var responseHandler: (URLResponse?) -> Void { get set }
    var httpResponseHandler: (HTTPURLResponse) -> Void { get set }
    var dataHandler: (Data?) -> Void { get set }
    var errorHandler: (NSError) -> Void { get set }
    var serverErrorHandler: (NSError) -> Void { get set }
    var errorDataHandler: (Data?) -> Void { get set }
}

All these methods, when implemented, will be run in the callback of a URLSessionDataTask. With all of these in place, we can define our wrapper protocol that holds all of these, and from which you can produce a URLSessionDataTask:

public protocol NetworkCall: class {
    associatedtype ResponderType: NetworkResponderProtocol
    
    var configuration: ServerConfigurationProtocol { get set }
    var endpoint: EndpointProtocol { get set }
    var responder: ResponderType? { get set }
}

It should be fairly simple to see how a dataTask can be constructed:

  • Generate a URL from the configuration and endpoint
  • Generate a URLRequest from that URL
  • Generate a dataTask from that request in the callback of which you call the responder‘s required functions on the parameters of the callback.

Deep Dive: fuikit

One of the projects that I’ve been working on, probably the one that is the most applicable for iOS development in a vacuum, is called fuikit (functional UIKit). Fuikit is comprised of subclasses of all the major UIKit classes (UIViewController, UITableViewController, UITableViewDelegate, CLLocationManagerDelegate, etc.), but abstracting all of the superclass’ methods into optional, settable functions. As a dumbed-down example, take FUIViewController:

public class FUIViewController: UIViewController {
      public var onViewDidLoad: ((FUIViewController) -&gt; Void)?

      override func viewDidLoad() {
             super.viewDidLoad()
             onViewDidLoad?(self)
      }
}

I’ve only written out viewDidLoad, but you can imagine filling all of the inherited methods in a similar way, each settable function variable taking an FUIViewController as a parameter in addition to ones the inherited functions take (onViewDidAppear, for example, is ((FUIViewController, Bool) -> Void)?).

This is one of the building blocks of the way that I’ve learned to develop mobile apps, and if you were to peruse the projects that I work on every day, you’d see the same paradigm popping up in a ton of files:

func viewController(styleVC: @escaping (ViewController) -&gt; Void, ...other parameters) -&gt; ViewController {
     //initialize vc
     vc.onViewDidLoad = ~&gt;styleVC // ~&gt; prefix operator optionally casts the 
                                                        FUIViewController into a ViewController and then 
                                                         runs styleVC if the cast is successful
     //configure vc in other ways
     return vc
}

class ViewController: FUIViewController {
     // outlets
     // vars

     override func viewDidLoad() {
           super.viewDidLoad() // this will call styleVC
           // other stuff that you want to happen 
     }
}

It forces you to be much more deliberate in when and how you want certain things to happen in the ViewController’s lifecycle. This way, you will never get a pesky crash from referencing an outlet before it’s been instantiated, because the interface you’re using to interact with your ViewController guarantees that. We generally always pass a styleVC parameter to handle tweaking the UI, and have a configure function that helps to populate the ViewController with data, whether that be through a network or just static data.

One of the advantages to the design of this library is that it’s completely airtight — anywhere you want to use a UIViewController, you can use a FUIViewController. The same applies with all the other superclasses. It also encourages the user to split up your styling, computation, and population, all while discouraging the user from the Massive View Controller. Writing a complicated View Controller is much harder when it gets to be hundred of lines long, and writing a complicated View Controller and then looking at your code and seeing the actual View Controller is only 8 lines long is also surprisingly rewarding.

Hello world!

My name is Calvin Collins, and I’m a 23 year old computer programmer, specializing in Swift and iOS programming. I also have experience in NodeJS, Rails, and ReactJS, but for the past couple of years my passion has been building iOS apps. I graduated from Williams College with a B.A. in both Computer Science and Economics, and currently living in Portland, OR.

While the first year and a half of my experience in app development was comprised mainly of youtube tutorials and StackOverflow, six months ago I got connected to Elliot Schrock (http://elliotschrock.com), who introduced me to a realm of Swift that enables things I hadn’t though possible. He runs an app consulting company called LithoByte, and I urge everyone who is looking to build an iOS app to look through his blog posts (linked above).

Over the past few years, Elliot has been developing not only fast and efficient applications, but also tools to make operations common across all apps doable with a tenth of the code. These tools are all publicly available on CocoaPods, and while useful in their own right, using them all together produces highly readable, easy code. As a full-time employee for LithoByte, I’m constantly using these new tools and developing new ones, and this blog serves both as a way to educate programmers on how to use these tools and why its useful, as well as a conduit through which we can gain input regarding how to improve our tools.

These tools have made coding in Swift so much easier for me, and I want them to do the same for you. Happy coding!

An Introduction to Functional Swift

As a recent graduate with a CS degree, my experience so far with computer programming is dominated by Object-Oriented-Programming, and more specifically “state-ful” programming. Thinking about it, it makes sense — abstraction is something we do all the time in the real world, so why wouldn’t we superimpose the way we perceive the world on the way that we approach programming problems.

A classic example that I’m sure anyone with a modicum of programming experience has encountered is the car: you see a car driving past you. That car has a make and model, velocity, drag, and a variety of other properties that vary in their importance to the perfectly realistic car-related problem you see in your high school or college intro classes. It’s ingrained into our minds from the get-go that state (what the object has) and behavior (what the function does) need to come together to form the holistic Object.

The problem is, in iOS development, current best practices aren’t “best” because they are the best, they are best practices because they are easy. You have a UIViewController that interprets user interaction, the UIView that contains the different user-facing elements on the application, and the model (and possibly viewModel) which handles computation. It’s the natural way to organize your app — any iOS programmer would probably take a look at their iPhone and come up with some version of this paradigm. But as your app begins to get more complex, it’s almost impossible for all these well-intentioned responsibilities to be independent of each other.

I don’t mean to say that this way of programming can’t create a good app — better programmers than I have stuck to this and that’s why it’s still used. This is just my way of looking at programming, and I think it’s the best way to make the foundation of your app quickly. There are obvious situations, involving custom behavior and animation that make your app unique, where taking a more OOP approach would suit better, but an advantage of functional programming is that it makes behavior stable, consistent, and repeatable.

An Introduction to Functional Swift (pt. 2)

In the first part of this delving into functional programming, I discussed its merits. This time we’ll actually be getting into some code! As a refresher to returning readers, or a short synopsis for new readers, FP at its core is simply dialing the state down as far as possible and replacing it with behavior or computation.

The biggest hurdle that prevented me from understanding the basics of FP was getting my mind around the fact that functions can be anything — when we think of functions in Swift, we think of this declaration:

public func doSomething(with x: Int) {
  //do something
}

when in reality, functions can be variables, parameter, closures, and return values. Again, this goes against the basics of what we’re told in school: if f(x) = y, f is a function that takes in a value x and returns a value y. In reality, with Swift’s relatively verbose type inference, neither x, nor y need to be actual values.

A great example of this that helped me fully understand the ideas behind functional programming is the operators in the CocoaPod, LithoOperators, which made functional programming much more intuitive for me. Take, for example, the compose operators:

infix operator &gt;&gt;&gt;: LeftwardAssociation
public func &gt;&gt;&gt;(_ f: @escaping (T) -&gt; U, _ g: @escaping (U) -&gt; V) -&gt; (T) -&gt; V {
    return { t in 
                     g(f(t))
             }
}

This is an infix operator that takes in two functions, (A) -> B and (B) -> C, and creates a new function that composes the two. You can take any two functions and chain them together, and then chain that function with another, and so on. This encourages the developer to think of computation in discrete stages, and therefore makes it easier to test (it is easier to identify where an error occurs in your code), and more readable — one big function with a single name alluding to input and output abstracts away everything accept for the first and last line in a function’s body. Naming many smaller, simpler functions and chaining them together provides a far more readable interface where any developer can infer the computation of a function call without actually looking at the function. Any iOS programmer with some spare time should take a look at the CocoaPod linked above, there are something like 40 different operators that make doing common operations like this a lot easier and readable.