Considerations in implementing MVVM in iOS with Swift

I’ve been researching iOS design patterns searching for new techniques for writing correct, fault-tolerant, and maintainable code as quickly as possible, and I’ve realized a terminological inexactitude has led to some confusion in design discussions I’ve had in the past. I think most people may be talking about implementing a layer of abstraction between the view controller and the model, delegating querying the model for information. This has it’s uses, but what I’ll be covering here is placing a layer of abstraction between the view and controller and calling that a view model.

One popular approach to application architecture in iOS is known as MVVM, or Model-View-ViewModel, developed by Microsoft around 2005. What I thought a view model was about was a “model” of a UIView’s desired input. Roughly, the “view model” of a UILabel would be a String, because you can set and get the string of the label. So imagine you had a custom UIView that looks something like this:

class ProfileView: UIView {
 @IBOutlet weak var userImageView: UIImageView!
 @IBOutlet weak var nameLabel: UILabel!
 @IBOutlet weak var biographyTextView: UITextView!

Instead of exposing the image view, label, and text view to the user of this class, which is desirable because the implementation of label or text view or that might very well change in the future, you “model” this view with a lightweight structure that looks something like this:

struct Model {
 let userImage: UIImage?
 let fullName: String?
 let biography: String?

Which enables you label the subviews of profile view as private and to write a derived property on your profile view that looks like this:

var model: Model? {
 get {
  return Model(userImage: userImageView.image,
  fullName: nameLabel.text,
  biography: biographyTextView.text)
 set {
  userImageView.image = model?.userImage
  nameLabel.text = model?.fullName
  biographyTextView.text = model?.biography

This allows you to hide the implementation of the view to users of it, define how you want the input of a view to be structured (“full name” or “first name” and “last name”, for instance), and you can then write extensions on your actual model layer to get the input you want. Like this, for instance:

class User {
 var image: UIImage?
 var firstName: String?
 var lastName: String?
 var biography: String?

extension User {
 var profileViewModel: ProfileView.Model {
   return ProfileView.Model(userImage: image,
                            fullName: "\(firstName) \(lastName)",
                            biography: biography)

Another way of implementing this pattern that might have some benefits if you’re interested in testing is with protocols. You won’t be able to add the model as a nested class of your view, which can make organizing code easier. Instead of having the view model generated in an extension, you could make the view model a protocol:

protocol ProfileViewModelProtocol {
 var userImage: UIImage? { get }
 var fullName: String? { get }
 var biography: String? { get }

And then instead of making the view model a derived property on the user, you add conformance to this protocol in an extension on your model:

extension User: ProfileViewModelProtocol {
 var userImage: UIImage? {
   return image
 var fullName: String? {
   return "\(firstName ?? "") \(lastName ?? "")"
 var biography: String? {
   return bio

And then the property of the profile view becomes something like this:

 var model: ProfileViewModelProtocol? {
  didSet {
    userImageView.image = model?.userImage
    nameLabel.text = model?.fullName
    biographyTextView.text = model?.biography

But this only defines communication one way. Models change. So how does this approach to MVVM tackle that? Let’s say the user can modify the biography in this profile. We’ll need to implement UITextViewDelegate on ProfileView and define a ProfileViewDelegate:

protocol ProfileViewDelegate: NSObjectProtocol {
 func biographyDidChange(_ biography: String)

class ProfileView: UIView, UITextViewDelegate {
  /* ... */
 weak var delegate: ProfileViewDelegate?
 func textViewDidChange(_ textView: UITextView) {

And the pattern all comes together in our hypothetical ProfileViewController:

class ProfileViewController: UIViewController, ProfileViewDelegate {
 @IBOutlet fileprivate weak var profileView: ProfileView!
 var user: User?
 override func viewDidLoad() {
   profileView.model = user
 func biographyDidChange(_ biography: String) {
   user?.bio = biography
   // inform API

To make this version clear, here’s a nice graphic I made for you:

This graphic makes the benefits clear in that there’s a level of abstraction in-between the view and the controller which is responsible for translating between the model layer and the view layer. If I find a good example of the other variety of MVVM, I’ll investigate and write up a post about it. Here’s a playground with all the code from this post.

Getting Laravel to use the Bootstrap 4 Alpha

I’m developing a Markdown-based notes taking platform with Laravel, and I want it to use all the latest and greatest CSS framework: the Boostrap 4 Alpha. To get this set up, I had to learn how web applications and Laravel maintains dependancies and packages code. The default site that Laravel generates has some links on the default page, and if you add the built-in authentication with PHP Artisan, those pages are served with an older version of Bootstrap. So how do you change this?

First, you need to add Bootstrap 4 Alpha as a dependency in the NPM dependency file “package.json” like, as well as Laravel’s version of Gulp called “Elixir” and it’s version of “Webpack”, another JS tool, like so:

"laravel-elixir": "^3.0.0",
"bootstrap-v4-dev": "^4.0.0-alpha.6",
"laravel-elixir-webpack": "^1.0.1"

You should then run NPM’s install to get the latest files. Now, navigate to the SCSS file in your Resources/Assets/SASS directory from your root Laravel directory. In app.scss, remove any unneeded lines, and make it look like this:

@import "node_modules/bootstrap-v4-dev/scss/bootstrap.scss";

This imports the new version of Bootstrap instead of whatever version your project came with. When we run Gulp, this will compile the latest Bootstrap SCSS files for your Laravel application, but we’ll also need to update the JavaScript file. Navigation to the Bootstrap JS file in Resources/Assets/JS, and make replace any mention of the Bootstrap JS (probably “bootstrap-sass”) file with this line:


With your dependancies installed and your assets pointing towards Bootrap 4, it’s time to set up Gulp so that you can compile these into your web application. Create a “gulpfile.js” in your root directory and add these lines:

var elixir = require('laravel-elixir');
var elixir = require('laravel-elixir');

elixir(function(mix) {

Now, when you run “gulp” in your root directory, you should find that your CSS and JavaScript have been updated to Bootstrap 4.

How I picked Laravel Homestead as my first backend development platform

As an experienced iOS developer, I interface all the time with backend services, and JSON RESTful APIs in particular. It’s a fairly common story for iOS developers to begrudge their work being blocked by backend holdups or bugs, and so, I thought I might as well try to try my hand at backend development to see if I could fix these problems myself.

Working on Apple platforms is simple. Language? Swift. OS? MacOS. IDE? Xcode. On and on, many questions have one answer. So you can imagine my uneasiness when asking the same questions on my first steps into backend development. Language? Uh, Ruby or PHP or Javascript or Java or … OS? Well, you can develop on whatever you want and you can run software on whatever you want, but probably something UNIXIDE? Well, what OS did you pick? And what language? And why aren’t you using Vim you filthy casual? (Emacs get out.)

Okay. I had some choices to make. I’ve heard from a few sources that backend should be old, boring, and crucially, reliable. I could think of no better candidate than PHP, and given that a few of the projects I’ve worked on have successfully deployed with PHP and I have some previous experience with it, it seemed like a reasonable first choice.

But I don’t want to fall into the trap of writing bad code, which I understand is easy to do in PHP, and I also don’t want to write code that has been written better by people that came before me. So I did some digging for PHP frameworks, and I found Symphony, CodeIgniter, and Laravel. The way that I picked one of these was the very scientific approach of picking the one with the most starts on GitHub, for better or worse, which at time of writing is Laravel.

I now set out to get a development environment up and running for Laravel, and to do that, here’s what you do. You’ll need to download Vagrant, which is a manager for virtual machines, VirtualBox, which is a virtualization engine, and Homestead, which is a nicely configured Laravel virtual machine. Homestead uses Vagrant which runs on VirtualBox.

To get this up and running, I found these tutorials very useful:

It took a while, but I now have it working, and I’m ready to start developing my Laravel app.

Display an HTML encoded String in a UITextView without changing characters to emoji

I wanted to display some text in a UITextView, and one of the glyphs was a Unicode checkmark, which I didn’t think anything of. But what I was finding was that when iOS rendered the checkmark, it was an emoji version instead of the boring old Unicode variant.

Before I ran into that issue though, I had to solve how to turn an encoded HTML string into something useable. A string like this:

<b>Hello</b><br><p>This is normal text.</p><br>

So I wrote an extension on attributed string to solve this problem, which uses some hackery to coax iOS into parsing and rendering the string for me:

extension NSAttributedString {
    convenience init?(htmlEncodedString: String) throws {
        if let data = .unicode) {
            let rawHTML = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil).string
            let styledHTML = "\(rawHTML)"

            if let htmlData = .unicode) {
                try self.init(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
            } else {
                return nil
        } else {
            return nil

It abuses the fact that NSAttributedString can take an NSData, which can understand HTML encoding, and then you can grab the decoded HTML string from it. At runtime, the raw HTML variable will look like:

<b>Hello</b><br><p>This is normal text.</p><br>

After that, NSAttributedString can understand this HTML and turn it into something you can render for the user. The weirdness comes when you include Unicode characters like the following:


I cannot guarantee that these are rendering the same on your machine, particularly if iOS has the same behavior in browser. For sake of precision, these values in encoded Unicode are supposed to be:

0x2709, 0x2714, 0x270C, 0x270D, 0x2764, 0x2600, 0x2602, 0x262F, 0x2622, 0x260E, 0x2744

But these were rendering in the UITextView as all emoji!? I found that solution was to use this scantily documented “Unicode variance selector” by suffixing the   violating Unicode values with it. Granted, I do not know if this is a definitive list of the Unicode values which do this on iOS, but I’ve wrapped all this up in an extension which you can use for your own purposes:

extension String {
    var escapingCharactersWithVariationSelector0E: String {
        var newStr = ""
        for unicodeScalar in unicodeScalars {
            switch unicodeScalar.value {
            case 0x2709, 0x2714, 0x270C, 0x270D, 0x2764, 0x2600, 0x2602, 0x262F, 0x2622, 0x260E, 0x2744:
                var escapedScalar = String(Character(unicodeScalar))

        return newStr

To wrap this all up, if you’d like to display:

var str = "&lt;b&gt;Hello&lt;/b&gt;&lt;br&gt;&lt;p&gt;This is normal text.&lt;/p&gt;&lt;br&gt; ✉✔✌✍❤☀☂☯☢☎❄▶◀"

You can use:

do {
    textView.attributedText = try NSAttributedString(htmlEncodedString: str.escapingCharactersWithVariationSelector0E)
} catch {

Please share the other Unicode values that do this! And check out the attached Playground which demonstrates the effect.


iOS development links: October 25th, 2016

iOS development links: September 22nd, 2016

iOS development links: September 21st, 2016

iOS development links: September 20th, 2016

iOS development links: September 19th, 2016

iOS development links: September 16th, 2016

Machine Learning in Swift: Linear Regressions

I’m going to implement a simple linear regression algorithm on a data set which maps square footage onto housing values in Portland, Oregon in Swift. With this algorithm, I’ll be able to predict housing values given square footage. For this exercise, I’m going to use pure Swift and keep my only dependency as Darwin. If you want to skip right to the code, here’s a Playground .

First, I’m going to need to define a point, with $x$ and $y$ values. If I were using CoreGraphics I could make use of CGPoint, but I won’t add that dependency and there doesn’t appear to be a Swift Point, which I find a bit surprising. Because Swift value types are much more efficient, I’m going to make my point a struct.

struct Point {
 var x: Float
 var y: Float

Great. Now I’d like to define a collection of points as an object so that I can perform operations on it. I’ll use a Swift Set because my data isn’t ordered.

typealias Data = Set

Unfortunately this is where I run into my first problem with Swift: my Point cannot go into a set because it’s not Hashable; and to be Hashable, the struct must also be Equatable. So let’s do some stuff to make the compiler happy:

func ==(lhs: Point, rhs: Point) -> Bool {
 return lhs.x == rhs.x && lhs.y == rhs.y

extension Point : Hashable {
 internal var hashValue : Int {
  get { return "(self.x),(self.y)".hashValue }

Now that I have all the preliminaries done, I’d like to define an extension on my new custom Point type which adds all of the functions I’ll need to perform a linear regression.

extension Data { }

This causes my second run-in with the Swift compiler: it seems that constrained extensions must be declared on the unspecialized generic types with constraints
specified by a where clause. This means that instead of using my custom Data object, I’ll have to use Set and constrain the Elements to Point structures. Let’s see what happens:

extension Set where Elements : Point { }

Unfortunately this also does not work: the compiler is complaining that I’m constraining Elements to a non-protocol type Point, which is true. I cannot quite tell, but it seems that this feature may be coming in a future version of Swift, along with the following syntax (which also did not work for me this time):

extension Set where Generator.Element == Point { }

In any case, I’ve now found the winning combination to get the functionality I want while keeping the compiler happy: a PointProtocol which defines an x and y, a Point struct which implements PointProtocol, and an extension on Set where the Elements conform to (the admittedly superfluous) PointProtocol:

protocol PointProtocol {
 var x: Float { get }
 var y: Float { get }

struct Point : PointProtocol {
 var x: Float
 var y: Float

extension Set where Element : PointProtocol { }

Now it’s time to implement the derivative values I’ll need to plot a linear regression on my Set of Points. With Andrew Ng’s first three lectures fresh in my mind and a little help from Salman Khan, I came up with the following implementation:

extension Set where Element : PointProtocol {
 var size: Float {
  get { return Float(self.count) }

 var avgOfXs: Float {
  get { return self.reduce(0) { $0 + $1.x } / self.size }

 var avgOfYs: Float {
  get { return self.reduce(0) { $0 + $1.y } / self.size }

 var avgOfXsAndYs: Float {
  get { return self.reduce(0) { $0 + ($1.x * $1.y) } / self.size }

 var avgOfXsSquared: Float {
  get { return self.reduce(0) { $0 + pow($1.x, 2) } / self.size }

 var slope: Float {
  get { return ((self.avgOfXs * self.avgOfYs) - self.avgOfXsAndYs) / (pow(self.avgOfXs, 2) - self.avgOfXsSquared) }

 var yIntercept: Float {
  get { return self.avgOfYs - self.slope * self.avgOfXs }

 func f(x: Float) -> Float {
  return self.slope * x + self.yIntercept

I have been trying to find a way to generalize the averaging functionality and pass in just the value I want to use in the summation, but I have yet to find a good way to do that.

Now that I have all the tools I’ll need, it’s just the matter of plugging in some data and running the regression:

var data = Data([
 Point(x: 2104, y: 400),
 Point(x: 1600, y: 330),
 Point(x: 2400, y: 369),
 Point(x: 1416, y: 232),
 Point(x: 3000, y: 540)

for var i in [0, 1000, 2000, 3000, 4000, 5000] {
 XCPlaygroundPage.currentPage.captureValue(data.f(Float(i)), withIdentifier: "")

This creates a beautiful graph in Xcode’s Playground which reveals to me the profound insight that a house with 0 square footage should be worth $267,900 in Portland, Oregon. More interestingly, at the 3000 square footage mark, just like we might expect by cross-referencing with out original data set, my linear regression shows the house should cost $522,146. Take a look for yourself:

Screen Shot 2016-02-14 at 1.06.43 AM


Mastering the iOS Technical Interview

General Questions

  • Can you describe your workflow when you work on creating an iOS app? Sure. iOS is like any other platform or programming environment, and at the beginning, you need to collect a complete or good initial set of program requirements. After you and your coworkers or clients are happy with the requirements, it’s time to start translating the program requirements into your software architecture. If dynamically updating content is a requirement, you’re going to need a backend. If caching or manipulation of content is required, you’re going to need a database, which will determine the structure and nature of your model. If a GUI is required, you’re going to need to define your views. You wrap these components together with a controller, and assure that your naming convention is semantically similar to your problem domain, downloadBusinessInformationFromBackend,storeBusinessInformationInBackground,updateViewForNewBusinessInformation, etc.

Continue reading “Mastering the iOS Technical Interview”

C and C++ Callbacks with SQLite

Everything is data. Occasionally, when programming day-to-day objects and functions, you get a reminder that everything from the keys you press to the code it makes to the bits it reads is data.

But enough, say you want to use C++ with SQLite in a sane, object-oriented way. More specifically, you want to use sqlite3_exec to execute a SQL query. Here’s an example:

int rc = sqlite3_exec(db, sql, callback, data, &errMsg);

What is each one of these parameters? The first, db, is your opened database, sql is a const char * query you want to run, callback is a static function pointer, data is a peice of data you want to send to callback, and errMsg is what it sounds like. Okay, all’s well, lets define that callback.

static int callback(void *param, int argc, char **argv, char **azColName)
    return 0;

Damnit. This is going to be called once for every row, I don’t know when it’s going to end, and it’s static, throwing any hope for object-orientation out the window.

Or does it? Switch gears for a moment: What’s one of the hallmarks of object-oriented programming? I’m talking about the keyword this or self. What this is is difficult to describe to others because you’ll often find yourself saying something like, “this is this, like you know, this is this”. But this can be thought of as a hidden parameter passed along with every message sent to an object which can access the object that the message was sent to.

Well if this is what we’re after, this is a hidden parameter, and we’ve got a void * we can put whatever we want in, how about we just reconstruct our instance of an object using C++ casting?

First, make your request:

char* customer::getPerson(int id)
    rc = sqlite3_exec(db, sql, callback, this, &errMsg);

Then, define your C callback with C++ casting to turn person into this:

static int callback(void *param, int argc, char **argv, char **azColName)
    Person * person = reinterpret_cast<Person *>(param);
    return person->cppCallback(argc, argv, azColName);

Finally, profit:

int Person::cppCallback(int argc, char **argv, char **azColName)

Thanks to this StackOverflow post for the insight.

Developer Journal: MVC and Interoperability

The desire for code re-use is a strong one among considerations of how to design a program or application. This competes with the desire to implement applications in their native, and oftentimes proprietary, framework.

Arguably the most important part of a mobile application to be developed natively is the view code. Non-native views on any sufficiently complex data-centered app are almost always immediately identified by users: web views and non-standard behavior almost always give it away. Furthermore, perhaps the least important part of an application to be native is the model. The storing, manipulation, and retrieval of data is oftentimes very similar across languages and frameworks: a linked-list is a linked-list no matter what language it’s in.

Perhaps we can use this dichotomy to best satisfy the competing desires of code re-use and native implementations: keep your views and controllers in native code, but implement your data model in shared code. Specifically, I’m wondering if I can move an application’s model to C++ on iOS, Android, and Windows Phone and only implement views and minimal controllers in native code.

In fact, ideally, all data-related tasks would be handy to have in shared code: anything involving databases, making requests to servers, and parsing responses are the taks which come to my mind. I think that in order to achieve this, I’m going to need to compile a framework for manipulating a database, a framework for making network connections, and a way to have native code request and receive data.

I think a design like this at least works, but it could even be desirable. Maybe the best way for me to find out would be to try it.

'The Productive Programmer' Review

It’s a natural obsession for programmers: the more effective code you can write in a fixed amount of time, the better. This obsession, which is perhaps better labeled a professional narcissism, is well-indulged by Neal Ford’s The Productive Programmer. The book’s central theme is that many of what makes computers highly usable also slows a user down, and that by taking inspiration from the way that the Super Clever People That Made Computers, we can make our use more effective.

Ford’s splits the goal of becoming more productive into two parts: the “mechanics” and the “practice.” Mechanics are about actual tools and code-snippets: using a launcher, a more advanced clipboard, terminal add-ons for your filesystem navigator, and even code snippets for scripts. While some of the software suggestions are a little dated even only a few years after publication, the take-away message is still intact: he describes the sorts of interactions you want to seek to have with a computer programmer.

You should avoid using the mouse when possible, you should minimize the amount of clicks needed when absolutely necessary, you should use searching to find applications, programs, and you should find a way to allow your computer to parse commands from your intent. More generally, The Productive Programmer advises you not to repeat yourself: if you tell your computer to do something, chances are you’ll want to do that again later, so automate it, speed it up, minimize the effort.

The “practice” that Ford describes is oriented towards software development advice, the sorts of methodologies and development styles that decrease wasted time. For instance, many if not all development shops use a version control tool, which allows a developer to revert to a version with an important code-snippet or a working build or whatever it may be. But there are many more tools and processes which can help equally as much.

My favorite of these was the advice to use a canonical build machine. I have squandered many hours setting up a new machine with old code, finding libraries and versions of programming languages and getting the right configuration. Instead, Ford advises you use a machine with has all the tools and libraries and version required to run your piece of software. With this sort of machine, it’s unambiguous how to run your app, and you can even image new machines from the canonical machine.

The Productive Programmer is an accessible introduction for the ambitious user/soon-to-be power-user. As should be expected, some of the tools Ford recommends are a bit dated (though most of them are still around). But the method and principles Ford exemplifies are simultaneously from a Golden Era of computing and a good vision for the future.

Consequences and Motivation

Being satisfied with good outcomes is a bad way of keeping oneself motivated. Satisfaction is a reward, it feels good, it is the very meaning of the word. Good outcomes feel good, otherwise I could not use the word good to describe them. So why should you not feel good about a good outcome?

Lets look at concrete examples and see if we can derive a general truth.

Fitness and health

This is an endeavor in which there are a lot of people which are very dissatisfied. I think this because of the sheer bulk of advertisements for gyms, diets, equipment, and supplements.

A good outcome in fitness and health is something like getting the body you want, lifting the amount of weight you want, or having the clear skin you want. These vary in difficulty, but those fitness and health goals that are especially valued by our culture are those which are hard, part of why we value them is because they are hard and not many people can acheive them.

Think about those advertisements and their content, the message they broadcast. These products are easy to use, work quickly, and “you will see results.” A gym equipment infomercial, in my experience, does not say that its product requires commitment, hard work, and will lead to countless failures.

And yet that is exactly what it is.

If you want to achieve a difficult goal in fitness and health, I find it likely that you should seperate your satisfaction from outcomes. You should not be satisfied when you look in the mirror and see the traits you want to have, you should attach satisfaction to the types of activities which give rise to having the traits you want.

If you find the process of becoming healthier and more fit rewarding, the intuitive psychological conclusion I draw is that you are then more likely to engage in the process more often, and thus, get the conclusion you want.

That’s right. In order to get something you want, you must first stop yourself from wanting it for the sake of getting it.

Productivity and programming

One of the many reasons I came to like computer programming is for the reward circuit. The first program you write is mysterious and you do not really understand what is at play, but your teacher guides you, you hit run, and sure enough, on the screen you see the words

Hello World!

And you think, I did that. And you find other things to do, more complicated, and by extension, more rewarding. But it takes more time to do, and more mental power, and you make more mistakes. There are an increasing number of times that you do not get that satisfaction like that first program, when you hit run and you get catastrophic failure and you do not know WHY.

So you hack away, running through every instruction set of your large, complicated program, and you see some errors and you fix them. You have less and less errors being printed out, and you are hunting down bugs when all of sudden you hit run and

Hello World!

It works. Your brain’s reward centers light up. You feel very satisfied.

I think this is young man’s style of programming. It is one of which encourages hacking together a set of instructions to see if it works, and then hitting run to get your fix.

The more desirable alternative is that you come to be satisfied with the process of programming. The really interesting problems are solved and understanding computer science happens by attaching your satisfaction to planning in advance your program’s structure, to reading about new concepts, and to coding every day.

The problems worth solving are likely not done in 24 hours binges, but instead, in consistently applying and honing your skillset. It is not that it is impossible, people do amazing work at hackathons all the time.

But being able to do amazing work at a hackathon comes from the process. The laudible outcomes in computer programming do not come from a series of binges, but in the process of programming, of taking your classes seriously, of learning something every day, of writing something every day.

What does this mean?

Self-improvement is not an outcome. There are outcomes that are in self-improvement, but self-improvement is a process. To be satisfied with an outcome in self-improvement is to separate the reward from the activity which gives rise to the outcome.

Those activities that are hard and worthwhile are going to make you fail. To be satified with outcomes is going to lead to a frustrating existence and make you more likely to give up. Love the process and find satisfaction in it, and you will be able to steadfastly endure failure after failure, which is the only way to meaningful success.

Consciousness and Assembly

The instructions that your computer’s central processing unit (CPU, the “brain” of your computer) uses to accomplish what you ask it to might be revealing about how your flesh and blood brain work.

How I came to the idea

I have started to read Jean Paul Sartre’s Being and Nothingness, and it is proving very rewarding. I chose to begin reading it for two reasons:

  1. I spend a lot of my time coding for class and for myself, but I only ever read for philosophy class, so I’m doing some outside of class philosophy work; and
  2. Existentialism is famously known to be a humanism, and I get the impression that (and this may be totally wrong) it is an inspirational breaking down of human psychology in this vast, scary Universe probably devoid of meaning or purpose, and I could use this right now.

But I am find myself a little nervous and skeptical while reading it.

Jean Paul Sartre and the existentialist movement place a lot of importance on and argue strongly for free will. Making choices is something central to their understanding of the human mind and reality.

I am convinced they are wrong, and find the arguments for hard determinism to be valid.

Hard determinism is the belief that given all the information about the speed, location, etc, of all the atoms and sub-atomic elements in the whole Universe and a sufficiently sophisticated understanding of how they interact, a mind could predict with 100% certainty what would happen in the future.

What more, but the objections to hard determinism do not lead to free will, but rather that we are only captive to the random tendencies of the matter which our mind is composed of. When Sartre is deep into explaining how anguish is the human emotional response that is generated when we notice the possibility of our non-existence and/or the non-realization of some desirable goal, and our continued choice to be and to do is to escape this anguish, I find myself both inspired and in agreement …

But ultimately disagreeing. And I can explain why with computer science.

Programming, assembly language, and machine code

All of the software you use on any of your digital devices, like your phone’s text messaging application or Microsoft Word, are programs, they are defined by code. It all looks something like this:

a = 5
b = 7
c = b + a

This program “outputs” the value 12.

Everything your programs are executed on the CPU using 0s and 1s, this is machine code. It all looks something like this:


And at a slightly higher level, these numbers can be defined by hex values, base-16 instead of the base-2 of the 0 and 1 flavor of machine code. It looks like this:

af ff 0a b3 f5

These are all just numbers. Data. ff in hex, for example, is the decimal number $255$. That binary number up top, all of it, is the equal to the decimal number $172,580$.

Wait! How does what I see in Word get defined in “code” that is ultimately made into just … 0s and 1s … How does my computer know what they “mean”?

The way that Word is made with code is with just more complex versions of the first example, where programmers make something like a “document view” program to build what you see, a “document model” defining how it is that your pages can look and how they are stored, and perhaps some sort of in between program that dictates how what you see interacts with what’s stored.

The way that your computer knows what 0s and 1s mean is by design! Clever scientists design a chip with a lot of densely packed on-off switches, and when the switches are turned on and off in a certain way, it triggers other on-off switches to go on or off in a predictable way. Furthermore, all the switches can be observed, so when you flip the switches, you can look at the “answer switches” to determine what happened.

Okay, I just about get it. But … uh, how does code become 0s and 1s?

With assembly code! Assembly is the human-readable intermediary between programming languages and CPU “on-off” instructions. Assembly code is defined by the people that make your CPU, and that definition is used by people that make programming languages.

And now you see how everything links up. You have MS Word, which is made with a high-level programming language. This is converted into assembly code for a given type of CPU. This assembly, in one way or another, is made into zeroes and ones.

Observe that your programs, your MS Word, is eventually just made into numbers, in data. That you programs are composed of the same stuff as the content you type into your Word document – values, content, data. Programs are data.

And this is a model I can use to reject free will.

How this all relates

It is in the common parlance and every introduction to technology textbook that the CPU represents the “brain” of a computer. The simile is a useful one because it actually represents the way that these things are. A CPU is used to make decisions about how your computer should operate in the same way that we have come to believe that the brain is the organ used to make decisions.

But these are never really decisions, they are merely computations.

When writing code, it is an illusion that your program is any way unique from a given set of numbers. It is a useful illusion that allows a programmer to extend the possibilities of useful and meaningful combinations of numbers to be fed to a processor.

I think that likewise, when making decisions, it is an illusion that your “decision” is any different from other types of events. The world-view of the determinist is one of events. Every event is preceded by the necessary prior events and followed by the necessary and inevitable future events. When a rock is triggered to roll down a mountain by a strong wind, the event is composed of a relatively large series of atomic events that let to its happening. With a sufficient understanding of the present condition, it would be possible to predict that the rock would be made to move. A meteorologist, geologist, and physicist could work together to accurately predict the weather, the threshold for moving the rock, etc.

In this metaphor, events are just “values”, just numbers. They represent a state of reality. I predict that as we learn more and more about smaller and smaller particles, that there will be some level at which either there is something or there is nothing. The aggregation of these atomic somethings and nothings forms progressively larger collections of somethings or nothings. Atoms represent a certain collection of somethings and nothings in that there is the “something” we have called the nucleus, the “something” we call the electrons, and there is the “nothing” in between the two groups. Additionally, a nucleus is composed of two types of “somethings”, protons and neutrons. We are finding that those are composed of there own types of “somethings”, which we presently do not know much about, but they are called sub-atomic particles.

I believe it is inevitable that there is some level of somethingness and nothingness which is atomic (not to be confused with atoms, which we now know are not atomic – whoops, Western science jumped the gun with that naming convention). Somethingness and nothingness can be thought of in terms of the binary number system, where one is something and zero is nothing. If you can assign this level zeroes and ones, you can assign progressively larger values to the aggregates of this something or nothingness.

If this is true, then all states of reality, all aggregate compositions of somethingness and nothingness can be assigned a value. Reality is data.

This would have consequences for the brain because it would mean that states of the brain, the configuration of a brain when it is holding a belief or performing an action, can also be reduced to values.

From the perspective of the brain, and admittedly I do not understand this at all rigorously, somethingness can be thought of as a neuron being “on” and nothingness can be represented by the neuron being “off.” In a series of firings of electrical impulses, states of the brain change. When you feel pain, neurons send “somethings” up to brain, and that changes the configuration of the ons and offs in a particular way, and you respond accordingly.

Furthermore, when you are presented with a decision, your brain gathers information about the decision using your perception, your sense organs. This is stored and is accessible. Using some decision making function, you appear to come to some conclusion and you enact it.

States of reality, under this model, are values. States of your brain and the beliefs and processes those states represent, are values. As physicists decode the language of reality and as neuroscientists decode the language of the brain, I predict that we are going to become increasingly aware that the Universe and our brains are complex machines. With this realization it will become increasingly clear that just as code being unique from data is an illusion, it is also an illusion that events in world are unique from states of reality, and it is also an illusion that decision-making is unique from the states of the brain.

This is exciting because it means as we come to understand the machines we make more and more and as they become more sophisticated, it will be revealing about the machine that makes and understands these increasingly sophisticated machines. Furthermore, as we come to understand the machine that we are more and more, we will be able to produce increasingly better reproductions of thinking.