turing complete with a stack of 0xdeadbeef

Writing by tag

Resources for learning about compilers and LLVM

Today I cleaned up my various projects and todo’s in OmniFocus. I am always collecting links and resources for potential project ideas, or for general learning. Sometimes, however, it is best to acknowledge that I will likely never have enough free time to even begin some of these endeavors.


What type is self in a Swift self-executing anonymous closure used to initialize a stored property?

The answer might surprise you

In JavaScript, this pattern is called an Immediately Invoked Function Expression (IIFE) or a Self-Executing Anonymous Function. Swift doesn’t have an “official” name for this, but IIFE works as well as “immediately executed anonymous closure” or “self-executing anonymous closure”. (Thanks to folks on Twitter for helping with this.)


Swift deinit is (sometimes) not called for throwing or failable initializers

I was never a fan of failable initializers in Swift. I do not think this is the correct place to fail and return nil most of the time. Of course, there are exceptions where a failable initializer is appropriate. But there is another behavior of which to be aware. When constructing a class via a failable initializer, init?() — or a throwing initializer, init() throws — the deinitializer, deinit, is not called if initialization fails or throws, respectively.


Swift globals and static members are atomic and lazily computed

While debugging some code the other day, I wanted to verify the behavior of global variables and static members in Swift. I vaguely remembered from the early days of Swift, that static let members and global constants were atomic and computed lazily — one of the many improvements over Objective-C.


Debugging a subtle Swift bug that will make you facepalm

The other day I was debugging a crash in a UI test for an open pull request at work. The bug turned out to be extremely subtle and difficult to notice. I spent way too much time staring at the changes, trying to understand what was wrong. Let’s see if you can spot the error.


Swift tip: Building arrays with compactMap

A common scenario in app development is to build up a list of objects, perhaps to display to the user or for another purpose. Maybe you’re fetching data from a database to display, or constructing fields to display for an interface. Consider the iOS Calendar app, for example. When you add a new calendar event, the form displays all the fields you can fill-in — title, location, date and time, notes, etc. However, when viewing an existing event all you see are the completed fields while the uncompleted fields are hidden.


Swift's new calling convention

From callee-owned to guaranteed

One of the major changes in Swift 4.2 is a change to the calling convention. But what exactly does that mean? Why is it important and why would you want to change it?


Thoughts on WWDC 2018

Community over technology

I had a great time at WWDC this year, meeting new friends and catching up with old ones. Those experiences are the ones that matter the most to me. The newly announced tech is interesting and fun, but ultimately fleeting and ephemeral.


Why optional closures in Swift are escaping

In a recent episode of the podcast, JP and I discussed the implicit escaping of closures in Swift. As Swift has matured and evolved, the default behavior of closure parameters in functions has changed. Prior to Swift 3, closures parameters were escaping by default. After SE-103, the default was changed to non-escaping.


Ending the Swift Weekly Brief

Taking an indefinite hiatus from writing the newsletter, and looking for a new owner

Next week’s issue of Swift Weekly Brief will be its 100th and final issue. I started this newsletter a little over two years ago, covering the initial open sourcing of Swift, the 3.0 release, the 4.0 release, and many significant milestones in-between for the language and the community. With few exceptions, there was a new issue every week thanks to the other amazing writers and contributors. The newsletter quickly became an important resource for the Swift community. Because of this, I’m sure many of you will be saddened to hear that the 100th issue will be the last. At least, Issue #100 will be the last issue for me, for now — but if someone from the community is willing to take over this project, it can continue.


Floating-point Swift, ulp, and epsilon

Exploring floating-point precision

Epsilon. ε. The fifth letter of the Greek alphabet. In calculus, an arbitrarily small positive quantity. In formal language theory, the empty string. In the theory of computation, the empty transition of an automaton. In the ISO C Standard, 1.19e-07 for single precision and 2.22e-16 for double precision.

The other day I was attempting to use FLT_EPSILON (which I later learned was laughably incorrect) when the Swift 4 compiler emitted a warning saying that FLT_EPSILON is deprecated and to use .ulpOfOne instead. What the hell is ulpOfOne? I read the documentation and then everything made sense — ha, just kidding. The FloatingPoint.ulpOfOne docs generously describe the static variable as the unit in the last place of 1.0 — whatever that means. Let’s find out.


Measuring Swift compile times in Xcode 9

Using -Xfrontend Swift compiler flags

The Swift type-checker remains a performance bottleneck for compile times, though it has improved tremendously over the past two years. You could even say the type-checker has gone from being drunk to sober. To help users debug these issues, awhile back Jordan Rose added a frontend Swift compiler flag that would emit warnings in Xcode for functions that took too long to compile, or rather took too long to type-check. In Xcode 9, there’s a new, similar flag for checking expressions.


A story about Swift source compatibility

How to add your projects to the swift-source-compat-suite and why you should

The Swift community has been through some rough migrations. It is frustrating when your project no longer compiles because of API and syntax changes, but it is an entirely different story when your project seg faults the compiler. When that happens, you cannot simply run a migration tool or apply fix-its — your project is broken and there’s little you can do until a fix is released. This is why the swift-source-compat-suite project was created.


Protocol composition in Swift and Objective-C

Designing optional semantics without optional methods

Protocols in Swift and Objective-C are a powerful tool to decouple your code. They allow you to specify a contract between classes that consume them, but defer a concrete implementation to conformers. They allow you to segregate interfaces and invert control. One interesting aspect of protocols in Swift and Objective-C is that protocol members can be optional (optional in Swift or @optional in Objective-C). Unfortunately, this comes with a number of disadvantages and diminishes the robustness of your code, so it is often avoided. However, having optional members is sometimes the right conceptual model for your design. How can you design your protocols to provide optional semantics without specifying them as optional or @optional?


Writing better singletons in Swift

Avoiding common pitfalls

In a previous post I discussed strategies for using singletons in a cleaner, more modular way. Singletons are a fact of software development, especially in iOS. Sometimes the design pattern actually is the right tool for the job. In those situations, how we can improve the way we write our own singleton classes?


Swift Unwrapped

Co-hosting a new podcast with JP Simard

A few months back, JP Simard and I decided to start a podcast about Swift — the language itself, its evolution and development, the Swift.org open source projects, and general Swifty news. There are a ton of great podcasts out there about developing for Apple platforms and Apple news, but there’s nothing exclusively about Swift the language. In many ways, this podcast is an extension of and commentary on the Swift Weekly Brief newsletter. However, we’ll be doing deep dives on various topics and elaborating on concepts in greater detail. I’m excited to share that we launched Swift Unwrapped yesterday with Spec.fm!


Refactoring singleton usage in Swift

Tips for a cleaner, modular, and testable codebase

In software development, singletons are widely discouraged and frowned upon — but with good reason. They are difficult or impossible to test, and they entangle your codebase when used implicitly in other classes, making code reuse difficult. Most of the time, a singleton amounts to nothing more than a disguise for global, mutable state. Everyone knows at least knows that is a terrible idea. However, singletons are occasionally an unavoidable and necessary evil. How can we incorporate them into our code in a clean, modular, and testable way?


Pushing the limits of protocol-oriented programming

Talk at Swift Summit in San Francisco

A few months ago, I spoke at Swift Summit in San Francisco. The conference has a reputation for providing high-quality talks, and this year was no different. Fortunately, I was able to see nearly all of the talks and not a single one disappointed me. It was such a great conference. The video and full transcript of my talk are now available. The videos of the other talks will be coming online over the next few weeks. I would recommend watching all of them!


Testing and mocking without OCMock

For Swift and Objective-C

OCMock is a powerful mock object unit testing library for Objective-C. Even if you are using Swift, as long as your classes inherit from NSObject, you can use some of its features. But what if you are writing pure Swift code which does not have access to the dynamic Objective-C runtime? Or, what if you don’t want your Swift code to be hampered by NSObject subclasses and @objc annotations? Perhaps, you merely want to avoid dependencies and use ‘plain old’ XCTest with Objective-C. It’s relatively easy and lightweight to achieve the same effect in some testing scenarios without using OCMock.


Shipping Swift 3.0

An update on my open source libraries

I’m happy to share that all of my open source Swift libraries have (finally) been updated for Swift 3. If you’ve been waiting for any of these final releases, you can now run pod update or carthage update and relax — sorry it took so long! I wrote about migrating to Swift 3 a few months ago and this post shares the final results of the process that I outlined in there.


Speaking at FrenchKit

Paris, France

Last week I attended and gave a talk at FrenchKit in Paris, France. As expected, it was an amazing conference — especially considering it was the first FrenchKit ever. I think the organizers are already thinking about FrenchKit 2017, so keep an eye out and definitely go if you can. I know I will.


Enums as configuration: the anti-pattern

Implementing the open/closed principle

One of the most common patterns I see in software design with Objective-C (and sometimes Swift), is the use of enumeration types (enum) as configurations for a class. For example, passing an enum to a UIView to style it in a certain way. In this article, I explain why I think this is an anti-pattern and provide a more robust, modular, and extensible approach to solving this problem.


Migrating to Swift 3

Advice, tips, and warnings

I spent most of my free time last weekend and a few days of last week on migrating my Swift code to Swift 3.0 — I migrated my open source projects as well as my private side projects. Overall, I would say my experience was “OK”. It definitely could have been better, but I think the largest problem was overcoming the cognitive hurdle of seeing all the changes and errors from Xcode’s migration tool at once. The best thing to do is wipe away the tears, put your headphones on, and start hacking. 🤓


Swift 3 sherlocked my library

Many of our "Swifty" wrappers are no longer necessary

What’s my favorite thing about Swift 3? Not maintaining third-party libraries that make Cocoa more “Swifty”. Swift 3 sherlocked my libraries, and I couldn’t be happier.


Avoiding the overuse of @objc in Swift

Don't let Objective-C cramp your style

A few days ago I was (finally!) updating a project to use Swift 2.2 and I ran into a few issues when converting to use the new #selector syntax introduced by proposal SE-0022. If using #selector from within a protocol extension, that protocol must be declared as @objc. The former Selector("method:") syntax did not have this requirement.


Open source everything

Getting meaningful contributions to move your projects forward

I recently had an incredible experience with one of my open source projects that I’d like to share. It’s a story of openness and collaboration that I hope other open source project maintainers will find valuable. This post continues the theme of “building successful open source projects” from my previous article on documentation.


Swift documentation

Writing, generating, and publishing great docs in Swift

The Swift community is ecstatic about Swift. There are so many new libraries being released each week that some have created package indexes — even IBM. But of course, a library is only as great as its documentation.


The new weekly brief

The Swift Weekly Brief gets a new home

In case you are late to the party, I finally found some time to give the Swift Weekly Brief a proper home. Starting this newsletter kind of happened by accident when I first wrote about the Swift open source announcement. Since then, it was kind of bootstrapped here on my personal blog and started to feel awkward. I hacked together the new site in a couple of nights and moved all the previous posts over. Today’s issue #5 is the first one to be originally published at swiftweekly.github.io. However, there is more here than just organization and a nice separation of concerns.


Open source Swift: weekly brief #4

What's been happening on Swift.org?

Now that the holidays are over, things have started to pick up again on Swift.org. If you are following any of the repos on GitHub, you have probably noticed. I’m not sure how I missed this before, but this week I just discovered SwiftExperimental.swift. For now, it defines a bunch of custom unicode operators for Set. It’s really cool. I would love to see more APIs like this in the standard library. Anyway, here’s the weekly brief!


Open source Swift: weekly brief #3

What's been happening on Swift.org?

As expected with the holiday season, things are slowing down for a bit on Swift.org. I have been traveling for the holidays as well, so this issue will be shorter than usual. If you haven’t already, be sure you take some time away from coding to enjoy the holidays and avoid burnout. Now, the weekly brief!


Open source Swift: weekly brief #2

What's been happening on Swift.org?

The Swift.org community is finishing up its second full week of open source development. If you were hoping for a quiet week, you will definitely be disappointed. There is still a ton of activity with no signs of slowing down. The Swift team continues to work openly and to be encouraging to contributors. This week brought more crash fixes and more Swift Evolution proposals. Let’s get to it — the weekly brief!


Open source Swift: weekly brief

What's been happening during the first full week on Swift.org?

It looks many developers in the community enjoyed my previous post detailing my thoughts and observations on the activity around the Swift open source project. So, I’m going to try to do this weekly — every Thursday, since the open source announcement was on a Thursday. Each week I’ll provide a high-level summary of what’s been happening, updates on interesting statistics, and links to interesting content. If you have any suggestions, please let me know! And now, the weekly brief!


Swift open source

Let the revolution begin

It has only been a few days since the announcement of Swift going open source and the activity around the project has been incredible. When Apple revealed that Swift would be open source at WWDC earlier this year, I do not think anyone anticipated a release like this.


Building type-safe, composable data sources in Swift

A modern approach to collection views and table views

In iOS development, the core of nearly every app rests on the foundations provided by UICollectionView and UITableView. These APIs make it simple to build interfaces that display the data in our app, and allow us to easily interact with those data. Because they are so frequently used, it makes sense to optimize and refine how we use them — to reduce the boilerplate involved in setting them up, to make them testable, and more. With Swift, we have new ways with which we can approach these APIs and reimagine how we use them to build apps.


Swift enumerations and equatable

Implementing equatable for enums with associated values

Recently, I came across a case (pun intended) where I needed to compare two instances of an enum type in Swift. However, it was an enum where some cases had associated values. At first glance, it is not obvious how to do this.


Namespaced constants in Swift

Using nested types for clarity

Mike Ash has a great Friday Q&A on namespaced constants and functions in C. It is a powerful and elegant technique to avoid using #define and verbose Objective-C prefixes. Although Swift types are namespaced by their module, we can still benefit from implementing this pattern with struct and enum types. I’ve been experimenting with this approach for constants in Swift and it has been incredibly useful.


Using Core Data in Swift

Talk at Realm in San Francisco

I recently gave a talk at the Swift Language User Group (#SLUG) meetup at Realm in San Francisco. A video of the talk is now online over at Realm’s blog, where it is synced up with my slides. If you haven’t already seen it, go check it out! Realm does an absolutely amazing job with posting these meetup talks — in addition to the video and slides, there’s a full transcript and subtitles.


Failable initializers, revisited

Functional approaches to avoid Swift's failable initializers

In a previous post, I discussed how Swift’s failable initializers could be problematic. Specifically, I argued that their ease of use could persuade or encourage us to revert to old (bad) Objective-C habits of returning nil from init. Initialization is usually not the right place to fail. We should aim to avoid optionals as much as possible to reduce having to handle this absence of values. Recently, @danielgomezrico asked a great question about a possible use case for a failable initializer — parsing JSON. Given this problem’s popularity in the Swift community, I thought sharing my response here would be helpful.


Functional notifications

Exploring the flexibility of Swift micro-libraries

The observer pattern is a powerful way to decouple the sending and handling of events between objects in a system. On iOS, one implementation of this pattern is via NSNotificationCenter. However, the NSNotificationCenter APIs are kind of cumbersome to use and require some boilerplate code. Luckily, Swift gives us the tools to improve NSNotificationCenter with very little code.


Better Core Data models in Swift

How Swift can bring clarity and safety to your managed objects

As I continue my work with Core Data and Swift, I have been trying to find ways to make Core Data better. Among my goals are clarity and safety, specifically regarding types. Luckily, we can harness Swift’s optionals, enums, and other features to make managed objects more robust and more clear. But even with the improvements that Swift brings, there are still some drawbacks and limitations with Xcode’s current toolset.


Swift, Core Data, and unit testing

Working around Swift's constraints to unit test models

Core Data is probably loved as much as it is shunned by iOS developers. It is a framework of great power that often comes with great frustration. But it remains a popular tool among developers despite its pitfalls — likely because Apple continues to invest in it and encourages its adoption, as well as the availability of the many open-source libraries that make Core Data easier to use. Consider unit testing, and Core Data gets a bit more cumbersome. Luckily, there are established techniques to facilitate testing your models. Add Swift to this equation, and the learning curve gets slightly steeper.


Swift failable initializers

When failable becomes fallible, and how to avoid it

Swift is still young and ever-changing. With each release, we have seen dozens of tweaks, additions, and deletions. And there is no reason for us to think that this rapid evolution will decline anytime soon. To remind us of exactly that, the latest post on Apple’s Swift Developer Blog introduces a new feature in Swift 1.1 in Xcode 6.1failable initializers.


Adaptive user interfaces

Exploring iOS size classes and trait collections

When the App Store launched, there was one iPhone with one screen size and one pixel density. Designing your user interfaces was relatively simple and the technical debt of hard-coding them was cheap. Today, developers and designers face many challenges in creating apps that must work on dozens of different devices. Long gone are the days of 480x320. We can no longer depend on physical screen sizes and must always be prepared for the next generation of devices.


Apples to apples, Part III

A modest proposal: can Swift outperform plain C?

When I find my code is slow or troubled, friends and colleagues comfort me. Speaking words of wisdom, write in C. It is understood that foregoing the features and abstractions of high-level programming languages in favor of their low-level counterparts can yield faster, more efficient code. If you abandon your favorite runtime, forget about garbage collection, eschew dynamic typing, and leave message passing behind; then you will be left with scalar operations, manual memory management, and raw pointers. However, the closer we get to the hardware, the further we get from readability, safety, and maintainability.


On the value of benchmarks

A brief examination of measuring code performance

As Apples to apples, Part II made its way around the web, it was praised as well as critiqued. The latter largely consisted of questions regarding the real-world applications of these benchmarks. In general, benchmarks should be taken with a grain of salt. I want to take a minute to clarify my thoughts on benchmarks and how I think they can be valuable.


Apples to apples, Part II

An analysis of sorts between Objective-C and Swift

If at first you don’t succeed, try, try again. Practice makes perfect. These proverbs have encouraged us all in many different contexts. But in software development, they tug at our heartstrings uniquely. Programmers persevere through countless nights of fixing bugs. Companies march vigilantly toward an MVP. But after 1.0 there is no finish line, there is no bottom of the 9th inning. There are more bugs to be fixed. There are new releases ahead. The march continues, because software is not a product, it is a process.


Apples to apples

A comparison of sorts between Objective-C and Swift

When Craig Federighi arrived at his presentation slide about Objective-C during this year’s WWDC keynote everyone in the room seemed puzzled, curious, and maybe even a bit uneasy. What was happening? As he continued, he considered what Objective-C would be like without the C, and the room abruptly filled with rumblings and whispers [1] as developers in the audience confided in those around them. If you had been following the discussions in our community about the state of Objective-C (and why we need to replace it) during the previous months, you could only have imagined one thing: Objective-C was no more — at least not as we knew it.