Favorite Swift 3.0 Features

Last week at WWDC was a massive whirlwind of learning, trying, and meeting. I had some time today to decompress and think more about some of the things that were released last week, starting with the Swift 3.0 beta.

There are a lot of amazing changes in Swift 3.0, but I wanted to highlight the ones that made me especially happy (i.e. I probably excitedly tweeted about it but want to say more than 140 characters about it).

Anyway, without further ado…

Importing Objective-C Lightweight Generics


Prior to Swift 3.0, Objective-C has had light-weight generics as a feature, which allows you to write code like ListViewController<Word *> * in Objective-C, but they used to appear to Swift code like ListViewController without the generic type parameter. In Swift 3.0, ListViewController<Word *> * will appear to Swift code like ListViewController<Word> instead, which is a huge improvement.

I’m particularly excited that Swift 3.0 will prevent me from writing layout code with NSLayoutAnchor that accidentally tries to constrain an X-axis anchor (like leadingAnchor) to a Y-axis anchor (topAnchor) because hey, we all make mistakes.

Type-safe layout code? I dig it.

If you’re interested in learning more about NSLayoutAnchor check out the official docs. 👀



Have you ever had to write stringly-typed KVO code like this?

person.addObserver(self, "phoneNumber.areaCode", options: .New, context: &context)

This is very prone to human-error like typos which will lead to crashes. Swift 3.0 adds a new expression #keyPath() which allows us to write the below code instead.

person.addObserver(self, #keyPath(Person.phoneNumber.areaCode), options: .new, context: &context)

Not only do we get the the benefits of static type-checking, we get autocomplete as well! Safe and lazy: my favorite kind of programming environment.

Import as Member


Have you ever had to write Core Graphics code in pre 3.0 Swift? I have, and it felt like I was writing C code! 😱

Lucky for us, Swift 3.0 adds the ability for C API authors to specify what the API should look like in Swift so it feels more natural, and well, more Swift-y. Look how much nicer the Core Graphics example looks now!

(If anyone knows if there is a replacement for UIGraphicsBeginImageContextWithOptions please let me know. EDIT: Thanks @alexito4 for the tip on UIGraphicsRenderer!)

Also, if you want to see an even bigger transformation of Core Graphics code, I recommend watching the Swift API Design Guidelines talk. The “Import as a Member” part is somewhere in the last 15 min or so.

Speaking of Swift API Design Guidelines, Swift 3.0 fundamentally changes the way that Swift code reads for the (way way way) better.

New API Design Guidelines


Swift 3.0 has three core principles:

  1. Clarity at the point of use (call site)
  2. Clarity > Brevity
  3. Reliance on contextual cues

I think the best way to experience these principles is to download Xcode 8 and run your code (maybe a small Playground at first) through the Swift 3.0 migrator. I tried it on a small project, and this is what I ended up with.

(Here’s the entire diff if you’re interested.)

You have to do some manual changes too (like choosing the right prepositions), but overall the migrator is 💯 and will do everything it can to make the transition process as smooth as possible.

Anyway, what do we read here?

  • “truncate to 8”
  • “sanitized string for key”
  • “hash for key”
  • “matches in line”
  • “localized strings in line”

Ah, grammatical code to my ears. 🎶

I love it.

If you want to hear more details about Swift 3.0’s philosophy, I again recommend watching the Swift API Design Guidelines talk. The official Swift API Design Guidelines page is a great companion reference as well.

… and many more

There are a tonne more features that were added in Swift 3.0, and you can learn about them on swift-evolution. Although I don’t follow the mailing list, I love skimming through the accepted and rejected proposals to see what kind of thought and reasoning went into each design decision. It’s especially interesting to read through the tradeoffs and alternatives that were considered, since this process applies to all sorts of engineering beyond programming language design.

I think it’s also worth noting that a lot of the “new” features that were added to Swift relate to having better Objective-C and C support, which may sound counter-intuitive/productive at first. But I think if we want the future to be Swift-y, we need to make sure that existing apps and frameworks that are written in Objective-C and C can seamlessly and naturally fit together with the Swift world, so that the entire community — not just the entirely-Swift apps — can proceed fearlessly into the new world. I think Swift 3.0 does a great job of building that bridge.

Anyway, thank you for reading! What are your favorite changes and additions to Swift? Let me know in the comments below. 🐥💛💭

Running the Swift 3.0 migrator on a standalone Swift file

The Swift 3.0 migrator works great on Xcode projects and Playgrounds. However, when I opened up a Swift script, which is a standalone Swift file, the Convert to Current Swift Syntax was not available in Xcode. 🐼

One workaround was to copy all of the script code into a Playground and do the migration there, but things got really annoying when I tried to import CommonCrypto (long-ish story for another time), and it also felt weird to have a Playground doing file I/O.

After going to the Swift lab at WWDC, some really helpful Swift engineers helped me out with a workaround solution. (Thank you!!)

All you have to do is run the follow line from the command line.

$ xcrun swift-update -sdk /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk -target arm64-apple-ios9 the-file-you-want-to-migrate.swift > the-output-file-name.swift

You might get a lot of output about what changed, but don’t mistake them for errors! Also make sure your Xcode beta is actually in Applications and not in Downloads or something because I had that issue/

If you are like me and are using CommonCrypto and have defined a module map for it to get it to work in a script, we can just ad the -I CommonCrypto option to get it to work property.

$ xcrun swift-update -sdk /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk -target arm64-apple-ios9 -I CommonCrypto the-file-you-want-to-migrate.swift > the-output-file-name.swift

Let me know if you have any questions, comments, or ideas. Happy Swift scripting! 🐥

Classes and Structs

Both classes and structs are the main building blocks of most applications. They help us organize our code into pieces that we can reason about more intuitively and with greater ease. Today, we’ll go over how classes and structs behave differently from each other, and finish off by starting to think about when to use a class vs. when to use a struct.

I highly recommend downloading the Playground or cloning the repo to follow along.

Let’s get started. ⚡️


Classes allow us to model many real world examples and help us organize and reason about our code. For example, we might want to make a shopping app. In our app, you can choose items, put them in a cart, and find out the total to pay.

We might model an “item” as below:

We can model a “cart” as below. It has a function total that calculates the total price of the items in the cart. (Don’t worry if you don’t know what reduce is, but feel free to look it up if you’re curious! 👀)

And now we go shopping! 💳

First, we need to buy a chicken hat. (Well, I need one. Why not?) I found a hand-knit wool chicken hat for $50 and a crispy green apple for $1. (I hope you like apples.) Let’s put those in the cart and calculate the total.

The total we expect to pay is $51. That seems like a pretty good deal, especially for such a high quality chicken hat. Let’s go and pay before we find the urge to buy more stuff.

While we’re strolling toward the checkout counter with the soon-to-be-ours chicken hat and apple, the shop decides to increase the price of the chicken hat to $1000. When they ring up our items at checkout, the total is $1001. We were expecting to pay $51. Not 🆒.

What happened here?

Classes are passed by reference meaning that there can be more than one reference to a given instance of a class. So in our case, we had a reference to 🐔 in our Cart instance, but we also had a reference outside the cart which allowed the shop to change its price on us unexpectedly.

So what’s the alternative to passing by reference? That’s where structs come into play.


In Swift, there are structs (short for “structures”). Like classes, they allow us to model many real world examples and help us organize and reason about our code. Unlike like classes, which are passed by reference, structs are passed by value.

Let’s see what happens if we make Item a struct instead of a class. All we have to do is change it from class to struct in our declaration.

Now let’s try shopping again. I still need my chicken hat and you’re still hungry for a green apple. We put those items in our cart, and the total is $51 as before.

Screen Shot 2015-11-29 at 14.19.22.png

The shop, again, decides to increase the price of the chicken hat to $1000 (maybe we should stop shopping here?). What’s the total in the cart?

It’s still $51. 🎉

What was different in the struct example compared to the class example? When something is “passed by value” (which is the case for structs, but not classes), the value is copied on assignment instead of sharing a reference. So when we created the items array like var items = [chickenHat, apple] that chickenHat was already different from the chickenHat from var chickenHat = Item(name: "🐔", price: 5000). If you’re curious, you can update chickenHat’s price right after we create items and see what the playground thinks is the value of items.

Screen Shot 2015-11-29 at 14.43.34.png

As you can see above, items has not changed.

However, if you do the same when Item is a class, you get the following result.

The chicken hat in items is $1000!

This is cool and all, but you might be wondering how structs and “value types” are even useful. Because in reality, you wouldn’t write such silly code that accidentally increases the price of the chicken hat, right? Imagine an app that’s been around for a while with a codebase of ten of thousands or more lines of code. On top of that, we’re in a multi-threaded environment because that’s the nature of our apps. Even if we are careful about not doing stupid things, accidents happen. When used effectively, value types can make code easier to reason about and follow, especially as our codebase gets bigger and more complex. 🌟

Value-types, everywhere

It’s also worth mentioning that value-types are nothing new. Take a look at this for example.

If Int’s were passed by reference, y would also be 2 at the end, but it’s not because it’s passed by value. In Swift standard library offers many value-types, including but not limited to Int, String, and Array. Structs are just another addition to this family, and we can start using them immediately.

At this point, I hope you have a lot of questions. Which brings us to the final part…

Learning More

I learned about reference-types vs. value-types back when I was first learning C programming, and I still remember how confusing it was and how much it didn’t make sense at first. Looking back and thinking about how I learned and am still learning, I think learning about values and references comes in two parts:

  1. Learning how structs and classes behave similarly and differently.
  2. Learning when to use structs and when to use classes.

I leave you all with some resources that I recommend for both parts.

1. Learning how structs and classes behave similarly and differently.

For this, I recommend experimenting in a Playground (maybe you can extend the example that we worked on today!) and reading explanations from many different sources. Hopefully, this post was also a good introduction to this. If you want to keep exploring, we only made Item a struct in our example, but what happens if we also make Cart a struct? What changes?

2. Learning when to use structs and when to use classes.

This is a much more nuanced and difficult topic, and for me, I’ve been learning mostly by trying things out and making mistakes. Luckily, some people have been writing and talking about what they’ve learned, so you can make fewer mistakes to start with.

  • Drew Crawford’s blog post Should I use a Swift struct or a class? The TL;DR: at the end of the post is a must-read too.
  • Mike Ash’s Q&A on when to use structs and classes.
  • Andy Matuschak on objc.io in which he discusses the “value of values” and the “object of objects” and more.
  • Boundaries by Gary Bernhardt goes over value-types and how to use them effectively with reference-types. This isn’t Swift-specific, but it’s a nice reminder that these concepts are relevant across different languages and problems.

One of these days I hope to have enough organized thoughts and opinions about when to use a class or struct based on experience and write about it. If you have any thoughts around specific cases of when it was better to a struct or class (or know anyone who’s written about their experience), let me know in the comments below! 😃

That’s it for now. If you have any questions, feel free to leave them in the comments below, or tweet at me @ayanonagon. The biggest reason I’m writing these posts is to get better at explaining concepts and how amazing they are, so any feedback about what was clear vs. not would be much appreciated as well. Also let me know what other topics you want to hear about. Hope you had fun learning, and thanks for reading! ☕️

What Year Is It?!

Today we’ll take a jog down memory lane starting with the release of Swift 2.0 at WWDC 2015 all the way to the announcement of iPhone OS at Macworld 2007. For some of you, it will inspire a mix of nostalgia and flashbacks, both good and bad. For others, this will be a glimpse into the past it was. There are many moments in this brief history that make me think, “What year is it?!” Although it’s 2015 and Swift 2.0 is new and shiny, I hope that we can look back a year, 2 years, 5 years from now and exclaim, “What year is it?!” because in the future there’s what we can only imagine, and so much more.

Hope you enjoy!


  • Swift 2.0 is released. guard, new error handling, fewer bugs, I love it! Plenty of great content on Apple’s WWDC page.


  • October 5: First commit to Carthage.
  • Swift is announced at the WWDC Keynote. This was the WWDC Keynote I had ever seen in person. I almost fell out of my chair. It was surreal.

Craig Federighi:

Objective-C has served us so well for 20 years. We absolutely love it. But we had to ask ourselves the question: What would it be like if we had Objective-C without the baggage of C? We did more than think about it. We have a new programming language. The language is called Swift, and it totally rules.

If you want to relive this moment, check out the keynote around 104:30.


  • instancetype keyword added to SDK. Before this, something like NSString *string = [NSArray array] would have compiled because NSArray’s +array method returned type id. 😱 What year is it?!
  • LLDB completely replaces GDB, which is no longer available with Xcode 5.0
  • More fun Objective-C things in Advances in Objective-C from WWDC 2013.


  • Properties become @synthesize’d by default. 💮
  • NSNumber, NSArray, NSDictionary literals and subscripting become a part of Objective-C. Remember +dictionaryWithObjectsAndKeys: and +dictionaryWithObjects:keys:count:? (You should listen to how much the audience cheered and clapped when this was announced at WWDC at the talk titled Modern Objective-C.)
  • Feb 26: First commit to ReactiveCocoa.


  • October 5: Steve Jobs passes away.
  • August 7: First commmit to CocoaPods.
  • May 29: First commit to AFNetworking.
  • Delivery of a fully featured version of ARC (Automatic Reference Counting) with iOS 5.

I love this quote by Chris Lattner when he was announcing ARC and saying good bye to manual memory management (WWDC 2011 Developer Tools Kickoff):

I hope you’re not too sad. I mean, maybe you’re attached to them. I can’t really help you out with that. You can choose to not use ARC if you want, but you really should just use it.

  • You can now add ivars in class extensions or directly in the implementation.
  • Natural scrolling is introduced with OS X Lion. I remember when this felt completely backwards. Now I can’t imagine going back.
  • Xcode is now free on the Mac App Store and only 3GB because they split it out into smaller packages! Xcode 4.0 was sold for $4.99 on the Mac App Store to the general public (non-Developer Program members) until 4.1 was released.
  • With Xcode 4.2, LLVM completely replaces GCC. 🐉
  • March 9: Xcode 4 is released, pulling Interface Builder into Xcode instead of having it a separate app. Imagine having to run Xcode, Simulator, and Interface Builder to do development with xibs.


  • June: iPhone OS is rebranded as iOS. 🆒
  • LLDB announced as a replacement for GDB.
  • WWDC tickets are sold out in 8 days. (WWDC 2010 Keynote)
  • iPhone has 28% of US smartphone market share.
  • Release of iPhone 4, which Steve Jobs compares to a “a beautiful, old Leica camera” during the keynote. This is the first iPhone that came with a Retina display, which contained 4x the number of pixels compared to a normal display. I can still remember where and what I saw for the first time in person in Retina. (It was the NYTimes website and Jim’s Steak in Philadelphia.) Can you remember the first time you saw it? ✨


  • Annoucement of iPhone 3GS and the 15" MacBook Pro with an SD card slot! Woooooo. (WWDC 2009)
  • January 18: First commit to three20. This is the first third-party library that I tried to use. The rest is history. Deprecated and archived.


  • July 10: App Store opens. 🎉
  • Steve Jobs introduces Enterprise and Ad Hoc app distribution. Also, the iPhone 3G. (WWDC 2008)
  • Phil Schiller announces MobileMe, as “Exchange, for the rest of us.”


  • January 8: Steve Jobs announces the iPhone OS at Macworld.

An iPod, a phone, and an Internet communicator. An iPod, a phone. Are you getting it? These are not three separate devices. This is one device. We are calling it iPhone.

I’ll leave the video here. You should watch it.

Thanks for reading! I hope you enjoyed it, and if anyone has any other fun bits of history that I missed or reactions, let me know in the comments below. Another fun question: What do you think will be announced next year or even more in the future? 🐥


If you’re used to Objective-C, you might be wondering if there’s anything special about Swift enums. The answer to that is a huge YES. Swift enums are way more powerful than Objective-C enums, and I promise you that you’ll love them. And for everyone else, you’re in for a treat as well.

You can follow along the code examples by cloning this repo or downloading the Playground directly.

We’ll first go over the basics, then dive right into some examples of how you can start using enums to write safer and more predictable code. ✨

Let’s get started.


Apple’s guide The Swift Programming Language describes enums as below:

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Maybe it’s because I’ve been writing a lot of UI code this week, but the first thing that comes to mind when I think of a group of related values I think of the idea of a “side” as in top, left, bottom, and right.

Turns out it’s really simple to define something like this in Swift:

You can even add raw values to your enums like Int below. The raw values are implicitly assigned as 0, 1, 2, and 3 respectively.


If we change Int to String, the raw values become "Top", "Left", "Bottom", and "Right" respectively.


At this point, you might be wondering 💭 “OK this is all cool but how can I start using this immediately?” Well I’m glad you asked! (Even if you didn’t, roll with me please. 🙏🏼)

One thing that we very often do in mobile development is talk to an API. Enums come in very handy when dealing with API’s. There are two main ways that come to my mind. The first is in API modelling and the second is in API response handling. Let’s dive in. 🐳

Enums applied to API modelling

If you are working on a messaging app, you might have a status for each message like Draft, Sent, and Failed. 📬

We can represent this as as Status enum like this:

Notice that we’ve explicitly assigned raw values instead of having them implicitly assigned. (Yes that’s another thing we can do with enums, 🆒!) You’ll see why we did this in a moment.

Next, we can use Status in our Message struct which might look something like this:

When we get a message from the API, it might come in JSON form that more or less looks something like this:

  "text": "Hello!",
  "status": "sent"

Wouldn’t it be nice if we could initialize a Message with the JSON dictionary that we get back from the API? Let’s see what this would look like.

(If guard is unfamiliar or new to you, please read Optional? which goes over everything you’ll need to know for this example.)

The most interesting line is

let status = Status(rawValue: statusString)

which is initializing a Status with a raw value. For example, Status(rawValue: "sent") would become Sent and Status(rawValue: "draft") would become Draft.

Here it is in action:


It’s such a small thing, but by using rawValue and explicitly assigning them to correspond to our API’s representations, we can write way nicer JSON deserializers and serializers without rolling our own functions that converts strings to enums and vice a versa (or worse yet, stringly-typing our code). If your API returns integers for statuses, all you need to do is change the raw value type to Int when you declare the enum, and the same pattern applies. Isn’t it so fun? 🐸

But that’s not all! I promised you two examples of using enums when dealing with API’s, so let’s keep going.

Enums applied to API response handling

When dealing with an API, there are many things that can go wrong. The request could fail because we have no network connection or the server is down, or maybe the request succeeds but we get malformed data.

Swift 2.0 changed the way that we handle error handling for most cases by introducing throws (more info on The Swift Language Guide). throws is great for guiding control flow (might write about it later if anyone is interested), but there’s one pretty big problem. We can’t use it for anything that is asynchronous, but asynchrony is the nature of API requests.

So now what? What if we wanted to hit the /messages endpoint to get a list of messages? One way we could do this is to have a completion block that provides an optional array of messages [Message]? and an optional error, like below:

The function listMessages takes in a completion handler completion that that takes [Message]? and NSError? as parameters. If the request is successful, completion gets called with messages with some [Message] result and error as nil. If it fails, completion gets called with messages as nil and error as some NSError.

This is a pretty standard approach, especially if you’re coming from Objective-C like I did. So is there anything wrong with it? Well, kind of.

What would you do if you got a result where messages is nil and error is nil? Or maybe you get non-nil messages but you also get a non-nil error. These are states that should be impossible, but they aren’t because we can write code that lets this happen. How do we write better code that doesn’t get into impossible states like these?

We prevent ourselves from writing bad code. ✋🏼

Swift enums have these things called associated values that let us write safer, more predictable code. Associated values are literally what they are called. You can associate values to your enums.

For example, we can define a Shape enum that has two cases Rectangle and Circle. Rectangles can be defined by a width and height, so we are going to associate width: Int and height: Int to Rectangle. Circles can be defined by a radius, so we are going to associate radius: Int to Circle.

Given this, we can now construct Rectangle’s and Circle’s.


Let’s apply this to our API request example. Our problem was that we could get into weird states with messages and error both being nil or both being present. Well, if we don’t want them to be together, why not split them in to different cases? Sounds like the job for an enum! We can declare an enum called Result that has two cases: Success and Error.

With this, we can update listMessages like this:

Now we can’t get into impossible states like having both messages and an error or having neither. Time to celebrate. 🎉

But wait. What if we wanted to use this beautiful Result type for handling API responses for other endpoints like /users in addition to /messages? We can make the enum generic on type T and have the associated value’s type for the Success case. (If you are unfamiliar with generics, please take a look at Generics first!) Note that we removed the names of the associated values messages and error because they were a little redundant and also optional.

For the /users endpoint, we can define listUsers like this:

Isn’t it so clean? Don’t you just want to go off and write yourself a beautiful API client in Swift?! Well even if you’re not quite as excited to that degree, maybe you’ve learned some things that you can start applying to your code immediately. At least that’s what would make me happy!

Anyway, that’s it for now. If you have any questions, feel free to leave them in the comments below, or tweet at me @ayanonagon. The biggest reason I’m writing these posts is to get better at explaining concepts and how amazing they are, so any feedback about what was clear vs. not would be much appreciated as well. Also let me know what other topics you want to hear about. Hope you had fun learning, and thanks for reading! 🐥

More reading

Swift Scripting by Example: Generating Acknowledgements for CocoaPods & Carthage Dependencies

We started using both CocoaPods and Carthage to manage our dependencies, and we wanted to add a nice little view in our app that shows a list of open-source acknowledgements and licenses. We have around 20 dependencies, and the thought of adding the acknowledgements manually sounded tedious and keeping everything updated every time we added/removed/updated a dependency sounded even worse. 💀

When something is tedious and requires repeating, it’s the worst. (Especially if you are lazy like me!) But the good thing is, with a bit of code we can automate all the things. We can take our laziness and do something fun. 🌟

Best of all, we can do this all in Swift!

Here’s the game plan.

  1. Get all LICEN(S|C)E files for CocoaPods and Carthage dependencies.
  2. Convert each license to Markdown.
  3. Convert the Markdown into HTML.
  4. Put the HTML file in our Xcode project.
  5. Load the HTML into a WKWebView (or UIWebView for < iOS 8) and show it in the app.

Steps 1-4 can live in a script, and once we write step 5 once, it will be automatically updated everytime we run the script. In our case, we took it one small step further and added it as a task to our Rakefile so we regenerate the acknowledgements HTML everytime we run rake (which also installs dependencies) so we can keep our licenses up-to-date when we add, remove, or update dependencies. (Thanks @_eliperkins for your help with this!)

Even if this isn’t the exact solution for the exact problem that you’re trying to solve, the concepts that we will go over here will be applicable to other Swift scripts that you might want to write.

Let’s get started.

Step 1: Get LICEN(S|C)E files for CocoaPods and Carthage dependencies.

When I learned that “license” can be spelled with two C’s as in “licence” I was very surprised. Anyway, let’s first see where we can find all of the licenses (and licences too I suppose).

  • CocoaPods LICENSE files live in Pods/[LibraryName] (like Pods/TZStackView/LICENSE).
  • Carthage LICENSE files live in Carthage/Checkouts/[LibraryName] (like Carthage/Checkouts/SSKeychain/LICENSE).

To find all of the LICENSE files, we can use NSFileManager and enumeratorAtURL. Turns out Foundation comes with some pretty useful tools for scripting when it comes to file I/O.

First, we get the URL’s for all files in Pods/ and Carthage/Checkouts/ which contain the LICENSE files for all of our dependencies. Feel free to follow along with the completed script acknowledge.swift. If you are unfamiliar with guard, I recommend reading “Optional?” first since guard will appear everywhere in this post. 💂🏼

Then we filter for just the LICENSE files.

… and convert them to License structs.

… where getLicense is defined as:

Step 2: Convert each License to Markdown

How do we convert these License’s into Markdown? That secret is in how we defined License which conforms to the Streamable protocol which we also defined.

Because License conforms to Streamable it needs to define a title and body. Based on this, the Streamable protocol provides writableString via a protocol extension that formats the License as a nice Markdown string with title as a h1 header style. (Apple has nice documentation around protocols and protocol extensions if they are new to you!)

Step 3: Convert the Markdown into HTML.

This is where things got a little bit interesting. I didn’t want to write my own Markdown to HTML converter. (Remember, I’m lazy.) @hyperspacemark found an open-source project called Markingbird 🐦 that does exactly this. But how do we get Markingbird added to our script? My first attempt was to add it as a Carthage dependency so we can import Markingbird but I quickly learned that there was no Carthage support for it. (I gave a talk on using Carthage as a dependency manager for scripting in Swift if you’re interested!)

Upon reading the README for Markingbird more thoroughly, I saw, the easiest way to use it is to simply copy that file into your own projects. Knowing that there isn’t a simple way to manage multiple files for Swift scripts, I copy-🍝’d the Markingbird.swift code, LICENSE and all into the top of our script.

And guess what. It looked horrible. I could barely tell where the actual script was which the many many lines of Markingbird.swift code added. We had to find a way to separate this code out.

After searching around, I found a Stack Overflow answer that suggested making use of the Unix command cat, which concatenates and prints files (type man cat into your command line to read the rest of the documentation). 🐱 Using this, we can cat Markingbird.swift acknowledge.swift which will print out all of Markingbird.swift followed by all of acknowledge.swift. We can then take that output and pipe it into xcrun swift as below:

cat Markingbird.swift acknowledge.swift | xcrun swift -

The - after swift means take stdin and run that. (If you’re curious you can read more about it.)

Anyway, voilà! It’s a bit weird, but it works and it’s very stable since all it does is use basic Unix commands.

Breaking News: While I was in the middle of writing this post, @hyperspacemark opened a pull-request to add Carthage support to Markingbird.

That means we can use the Carthage method to add Markingbird to the script. ✨ In Cartfile.private (.private because we’re not shipping this into our app, check out the documentation), we can add Markingbird as below:

github "venmo/Markingbird" ~> 1.13

(Until this pull request is merged in and a new release is cut, we can point to venmo/Markingbird instead of kristopherjohnson/Markingbird.)

When you run carthage bootstrap, Carthage builds the frameworks and outputs them to Carthage/Build/iOS (and/or Mac, watchOS, tvOS depending on what platforms the framework supports). And the swift command lets us specify a framework search path with the -F option. We can run acknowledge.swift with that option like below:

xcrun swift -F Carthage/Build/Mac acknowledge.swift

And in acknowledge.swift, we can import Markingbird.

I don’t know about you, but I don’t want to type xcrun swift -F Carthage/Build/Mac acknowledge.swift all the time. 😪 It’s pretty long and it very much defeats the purpose of scripting. The good thing is, we can make it so that we have to only run ./acknowledge.swift with 2 simple steps:

  1. Run chmod +x acknowledge.swift to give it executable permissions.
  2. Put #!/usr/bin/env xcrun swift -F Carthage/Build/Mac at the very top of acknowledge.swift. This is an interpreter directive that specifies how to run this file.

Now, all we have to type is ./acknowledge.swift to run the script. 🎉

But before we do that, let’s finish up the script. Our last step is to convert the Markdown to HTML and write it out to a file. We can do this in three lines of code.

You can take a look at the script in all its glory here. We plan on making this more generic and open-sourcing it properly, so keep an eye out on github.com/venmo! 👀

Step 4: Put the HTML file into our Xcode project.

In our script, we output the generated HTML into our Resources directory. Once you add it to the Xcode project once, it’ll get updated automatically when you run the script. Unless you also commit your Pods and Carthage directories (which is fine, just different philosophies), you probably want to put your HTML file into .gitignore as well since it’s a build product that is generated automatically.

Step 5: Load the HTML into a WKWebView (or UIWebView for < iOS 8) and show it in the app.

At this point we’re done talking about things that are specific to scripting, but if you’re curious about this web view business, feel free to follow along.

Both WKWebView and UIWebView have a method called loadHTMLString(_:baseURL:) that lets you load an HTML string directly in the web view. So in our case, we want to load the entire mega HTML string that we generated into this method.

And that’s it! Once you apply some basic CSS to the HTML, you will end up with something like this. (We’re still tweaking the CSS to make it look better as well.) Because we hooked in the call to ./acknowledge.swift to our Rakefile to have it get called right after updating any CocoaPods or Carthage dependencies, we never have to worry about about adding/deleting/updating our licenses again. Time to kick back and relax. 😎


That’s it for now. This piece goes a little beyond the basics compared to my other step-by-step posts, but I thought it might be fun to start writing a bit about different applications of Swift as well. If you have any questions, please feel free to leave them in the comments below, or tweet at me @ayanonagon. The biggest reason I’m writing these posts is to get better at explaining concepts and how amazing they are, so any feedback about what was clear vs. not would be much appreciated as well. Also let me know what other topics you want to hear about. Hope you had fun learning, and thanks for reading. 🐣

I’m also incredibly curious what others have been doing for Swift scripting, like what you do for dependency management and what you are automating with the scripts, so please let me know in the comments below! 📩


Favorite Explanations (of things that made my head hurt)

There are some Swift concepts that really made my head hurt when I was first trying to grasp the concepts. Here are some of my favorite explanations for some of the things I found most difficult to understand. Hope you find them useful as I did!

Associated Types: Using Generics with Swift Protocols

It’s easy to get into a nightmare spaghetti situation of types when you’re first starting with Swift protocols, especially if you try to genericize them. Russ Bishop has a great, easy to follow explanation where he walks you through the “wat?”s of Swift’s associated types.

Should I Use a Struct or Class?

Many people will tell you that you should use struct as much as you can (including me!). But from experience, I have run into cases where I was bending over backward like a dried up Gumby doll to make something a struct, and it ended up being way cleaner when I turned it into a class. Drew Crawford has a great guide for choosing between a struct or class if you ever find yourself in a similar situation. Thanks @hyperspacemark for showing me this!

[weak self] vs [unowned self]

In Swift, like Objective-C, we still have to worry about retain cycles. Even if you are familiar with weak vs strong, unowned might be something new to you. Hector Matos has a fun explanation of when to use [weak self] vs [unowned self] that you should definitely check out! TL; DR: “If you can guarantee that the reference will not be nil at it's point of use, use unowned. If not, then you should be using weak.”

🙌🏼 Let me know what you think of this format! If you like it I can continue having posts like these in addition to my longer form explanation posts. Thanks for reading!


Generics are one of my favorite features of Swift. Like Optional, it makes your code safer to work with, makes your app have fewer crashes and unexpected bahaviors, and at the end of the day, it makes your users happier. It’s one of the core features of Swift that make it great language to work with, and I think you’ll love it as well. Without further ado, let’s get started!

Let’s say you want to define a struct that lets you have pairs of things. Maybe we can call it Pair. (I recommend downloading the example Playground or cloning the repo and following along. This one has multiple modules so make sure Xcode’s Project Navigator is visible by pressing ⇧⌘J.)

struct Pair {
    let first: String
    let second: String

Then you can create a Pair of Things, like:

let things = Pair(first: "Thing 1", second: "Thing 2")

This is pretty useful! It’d be nice to be able make pairs of other things too, like the result of two dice rolls like below. 🎲🎲

let snakeEyes = Pair(first: 1, second: 1)

But we get an error Cannot convert value of type 'Int' to expected argument type 'String'.

That’s kind of a bummer. What if we really do want to use this in other places? What if we wanted to make it a little more… generic? That’s where the aptly named generics come in handy! 😏

We can redefine Pair as below. Note the addition of <T> and T for both of the types.

struct Pair<T> {
    let first: T
    let second: T

If you’re trying to figure out how to read this out loud, I’d probably say something like “Pair is a struct that is generic on type T and has two properties: first of type T and second of type T.”

Now we can do all things.

let things = Pair(first: "Thing 1", second: "Thing 2")
let snakeEyes = Pair(first: 1, second: 1)

You can even make a Pair of Pairs if you wanted to!

let pairOfPairs = Pair(first: Pair(first: "First First", second: "First Second"),
    second: Pair(first: "Second First", second: "Second Second"))

Magical, eh? And who said pairs of things have to be of the same type? What if "Thing 1" wanted to hang out with 1 for a change? Let’s try it.

let ones = Pair(first: "Thing 1", second: 1)


🚨 Cannot invoke initializer for type 'Pair<T>' with an argument list of type '(first: String, second: Int)' 🚨

The error is saying that we can’t create a Pair that has different types for first and second because we said they are both type T. How do we fix this? We add a another generic to Pair!

struct Pair<T, U> {
    let first: T
    let second: U

Pair now is generic on T and U, where first is of type T and second is of type U. If we try to initialize ones again, it now works.

let ones = Pair(first: "Thing 1", second: 1)

It’s old convention to use T (for “Type”), U, V, etc. to signify the generic type, but you can really name it anything. @UINT_MIN pointed out that Swift is moving toward more descriptive naming, like Optional.Wrapped and Array.Element. I also learned today that you can even use emoji 😻 (with a few caveats so see the full list of allowed emoji). Thanks @jckarter and @nnnnnnnn!

Even if you don’t find yourself defining your own classes and structs that are generic immediately, I bet you’ve used them before whether you knew it or not.

As programmers, we very often work with arrays. On any given day, you might declare an array of monkeys. Sometimes, we get sleepy, doze off a bit, and accidentally try to insert a number into our array of monkey emoji. 😪 But Swift being Swift, the compiler has our back and says: Cannot convert type 'Int' to expected argument type 'String'.

How did Swift know that we can’t do that? Because Swift is good at figuring out what type something is, when we write var monkeys = ["🙈", "🙉", "🙊"] it infers to the type of var monkeys as below:

var monkeys: [String] = ["🙈", "🙉", "🙊"]

Another way to write this is…

var monkeys: Array<String> = ["🙈", "🙉", "🙊"]

Look! Those angle brackets. They look familiar. They are our good friend generics. var monkeys is of type Array<String>. If you look at Apple’s documentation on Array, you’ll see that Array is defined as struct Array<Element>. (“Array is a struct that is generic on type Element.”)

If you scroll down a little further, you’ll find the documentation for the append function.

Aha! append takes type Element as a parameter, Element as in the type that Array is generic on. So if we initialize var monkeys with type Array<String> we have to call append with a String and Int won’t work. And now you know.

Generics are everywhere in the Swift Standard Library and you’ll definitely be using them all the time. If you’re curious, I recommend perusing through the library and see where you see classes and structs that are generic on some type. (Just look for those angle brackets!)

That’s it for now. If you have any questions, feel free to leave them in the comments below, or tweet at me @ayanonagon. The biggest reason I’m writing these posts is to get better at explaining concepts and how amazing they are, so any feedback about what was clear vs. not would be much appreciated as well. Also let me know what other topics you want to hear about. Hope you had fun learning, and thanks for reading!

Recommended Reading


You might have overheard Swift developers talk about how great Optionals are. Optionals are a foundational feature of Swift, and once you know how to use them, you probably wouldn’t even want to work with a language that doesn’t support it. If you’ve ever had your app crash because your code allowed nil to be inserted into a NSDictionary 💣 or had text in a UILabel show up as (null) or anything else bad caused by nil, you’ll love optionals even more.

Let’s start with a small example. (I recommend downloading the Playground project or cloning the repo and following along!) Let’s say you want to model a Person, and you want a person to have a given name, family name, and middle name. You might define such a Person like this:

struct Person {
    let givenName: String
    let familyName: String
    let middleName: String

Now, I can create a Person to represent myself. I don’t have a middle name, so I’m going to pass in nil for that.

let me = Person(givenName: "Ayaka", familyName: "Nonaka", middleName: nil)

Hmmm. I got an error message: Nil is not compatible with expected argument type 'String'.

This is because the Swift compiler is warning us, “Hey, middleName can’t be nil because you didn’t say it could be nil!” But how do we tell the compiler that it’s OK for middleName to be nil?

That’s where Optional comes in. We can redefine Person as below:

struct Person {
    let givenName: String
    let familyName: String
    let middleName: String?

Notice that now middleName is of type String? instead of String. This means that middleName can be a String or nil. Now

let me = Person(givenName: "Ayaka", familyName: "Nonaka", middleName: nil)

should compile without error.

Let’s take it a little further and add a computed variable that returns a Person’s display name. For example, mine would be “Ayaka Nonaka” or if I had a middle name, maybe “Ayaka Chewbacca Nonaka” or something like that. 🙊

struct Person {
    let givenName: String
    let familyName: String
    let middleName: String?
    var displayName: String {
        return givenName + " " + middleName + " " + familyName

Slight problem here. This doesn’t compile! 😭

You get a somewhat cryptic warning Value of optional type String? is not unwrapped; did you mean to use '!' and '?'. You even get a friendly looking Fix-it from Xcode to Insert ”!”. It’s a trap. Don’t do it!

The ! suffix is used for “force unwrapping” optionals, and you’re telling the compiler that you swear that this will never be nil, even though it’s an optional. If you’re not careful, this can lead to runtime crashes which is really not fun when it happens in production when it crashes for your users.

So how do we appease the compiler without yelling! at! it! by! force! upwrapping? If you’re coming from another language, your first instinct might be to check for nil like below:

var displayName: String {
    if middleName != nil {
        return givenName + " " + middleName + " " + familyName
    } else {
        return givenName + " " + familyName

But you’ll notice that we get the same error message as before. The problem is that even though it might look obvious to you that middleName can’t be nil within the if, it’s not obvious to the compiler.

If you thought if statements were useful, wait until you see this one. Introducing… if let!

if let

An if let statement looks something like this:

if let x = y { // where y is Optional
    A(x) // Do something with non-Optional x

You can read this as: If y has a non-nil value, assign it to x and execute A and it’s guaranteed that x is non-nil.

In our case, we can rewrite displayName as below.

var displayName: String {
    if let middleName = middleName {
        return givenName + " " + middleName + " " + familyName
    return givenName + " " + familyName

You might notice that we used the same variable middleName for the left and right-hand sides of the if let. We could have written if let actualMiddleName = middleName or something like that to make it very clear that the left handside is the non-optional, but I personally prefer using the same name for both because it’s cleaner and easier to read. (Download the if let solution.)

There’s one more thing I want to show you. They’re called guard statements.

guard 💂🏼

If I had to choose a favorite feature that was introduced in Swift 2.0, it’s guard. A guard statement looks like this:

guard let x = y else { // Where y is Optional
    A(y) // Do something with y as nil
// Do something with non-Optional x

You can read this as: If y has a non-nil value, assign it to x. Otherwise, execute the else clause assuming y is nil. Below the guard, you can use x which is guaranteed to be non-nil.

Let’s see how we can rewrite displayName using guard instead of if let. It might look something like this:

var displayName: String {
    guard let middleName = middleName else {
        return givenName + " " + familyName
    return givenName + " " + middleName + " " + familyName

That looks pretty similar to our if let example. Why would we even use it over if let then? Let’s look at a slightly more complex example.

When we make apps, we often have a backend API that we are communicating with. The API sends us back data (often in JSON format), and we have to convert that to something that we can work with on the client side. In our Person example, it might be nice if we can initialize a Person using a JSON dictionary that we get back from the API. First let’s see what this might look like using if let.

init?(dictionary: NSDictionary) {
    if let givenName = dictionary["given_name"] as? String,
        let familyName = dictionary["family_name"] as? String {
            self.givenName = givenName
            self.familyName = familyName
    } else {
        return nil
    self.middleName = dictionary["middle_name"] as? String

A couple of things to point out here:

  1. Yes, if let lets you assign multiple values at once. It’s awesome.
  2. init with a ? is known as a failable initalizer. We won’t get into it here, but if you want to read more about them, Apple’s Swift blog has a great post about it.

Anyway, yikes. I don’t know about you, but this looks pretty complicated for something that does a relatively simple task. What’s going on here? First, we’re seeing if dictionary["given_name"] is a String (non-nil since it’s not String?) and assigning it to givenName and doing the same for dictionary["family_name"] for familyName. If both of these are non-nil we assign to their respective properies. Otherwise, we return nil and fail the initializer. Finally, we set middleName outside of the if let because we’re fine if middleName is nil since it’s of type String?.

We can do better than this. Let’s see what this would look like with guard.

init?(dictionary: NSDictionary) {    
        let givenName = dictionary["given_name"] as? String,
        let familyName = dictionary["family_name"] as? String
    else { return nil }
    self.givenName = givenName
    self.familyName = familyName
    self.middleName = dictionary["middle_name"] as? String

Before we dive into the code itself, step back and look at it for a second. Compare it to the if let solution. Doesn’t it just look cleaner?

Just like the if let example, we’re first seeing if dictionary["given_name"] is a String and assigning it to givenName and doing the same for dictionary["family_name"] for familyName. Unlike the if let example, if either of these turns out to not be String, it falls into the else clause and fails the initializer, because we don’t ever want to end up with a Person without a givenName and familyName.

Now below the guard we can happily work with givenName and familyName knowing that they are both String and assign them to their respective properties. As for middleName, its type is String? so we’re fine if it’s nil and we don’t have to guard against its being nil.

This is clean and easier to understand because the “happy path” where a Person can be created is all in one place, unindented, unnested, and easier to follow. (Download the guard example.)

Isn’t guard so nice? I didn’t think working with JSON dictionaries could be this pleasant without having to rely on frameworks like Mantle (which was a must have for me for Objective-C). If you want more information about errors though, like when the API starts returning data with missing fields and you’re trying to figure out what’s missing, you might want to check out Argo.

That’s it for now. If you have any questions, feel free to leave them in the comments below, or tweet at me @ayanonagon. The biggest reason I’m writing these posts is to get better at explaining concepts and how amazing they are, so any feedback about what was clear vs. not would be much appreciated as well. Also let me know what other topics you want to hear about. Hope you had fun learning, and thanks for reading!

More Reading