turing complete with a stack of 0xdeadbeef
Perhaps “quirks” is not the correct description, but I recently encountered some unexpected behavior when modifying a protocol in Swift. While I was initially slightly confused, how Swift handles protocol requirements does make sense — conformances are more lenient than you might think!
Foundation’s URL
(née NSURL
) is a nearly ubiquitous API on Apple platforms. One of its shortcomings is that it is heavily overloaded – an instance of URL
could represent a web URL or a file URL. While there are many similarities between accessing resources on a local disk or on a web server, I think there should be explicit types for each, say WebURL
and FileURL
.
When I first wrote about DocC, I lamented the fact that it was incompatible with static hosting on GitHub Pages. Much has changed since my last post, so let’s take a fresh look. While there have been many welcome improvements to the tool, there are a few remaining issues that prevent me from adopting it for my open source projects.
In Swift there are 13 numeric types. Like most other programming languages, Swift provides signed integers of various sizes, corresponding unsigned integers, and a few floating-point types. But if you’ve been developing apps for Apple platforms for any amount of time, you’ll recognize another numeric type — Decimal
(aka NSDecimalNumber
). When we build the model layer of an app, it’s important to choose the right type for the task we want to accomplish. For example, if we are counting ticket sales for an event, then Int
(or possibly UInt
) would be the most appropriate type. But if we are calculating sales tax, then we’ll need to use a floating-point type. You likely know that Double
is more precise than Float
, but what about Decimal
? When should you reach for Decimal
instead?
A recent post from Tom Harrington explores the issues with optional and non-optional values in Core Data regarding how the framework interacts with Swift. It’s a good overview. You should read it. The post shares some workarounds to improve the situation, but I want to share how I solve these issues in a more robust way.
I’ve spent this past week diving into SwiftUI, seriously, for the first time. As you know, I’ve been keeping my eye on it since it was released, but I’ve avoided it due to a combination of hesitancy, apprehension, and just being too busy with other projects and work. However, while taking some time off from contracting work, I decided to dive in.
I’ve decided to deprecate one of my open source libraries, PresenterKit. The library has been in a sort of “maintenance mode” for awhile now. It never really became what I hoped and anticipated. I think it implemented some neat ideas and helped removed some boilerplate from UIKit, but I don’t think what it provided necessarily justified a library anymore — at least not given the lack of activity around the project.
I came across a situation today where I needed to run an iOS test suite for a Swift Package. Previously, this required you to have an Xcode project but it no longer does.
After I wrote and released Foil, my library for implementing a property wrapper for UserDefaults
, one of the criticisms on Twitter was that a mechanism for observing such properties should have been included. I disagreed. In the post I argued that this was easy enough for clients to handle on their own, but more importantly that there are too many options for how to do this and I didn’t think Foil should impose any one of them on clients.
I’ve been following what’s going on with SwiftUI since it was released with iOS 13 at WWDC 2019 and have even taken extensive notes, but I have avoided using it. As I wrote before, I mainly wanted to avoid dealing with bugs and workarounds that might make me less productive compared to using UIKit, which I know quite well. I’m very interested in learning and using it, I’m just hesitant given some of Apple’s history, like early years of Swift. I have no doubt that SwiftUI will be the future of Apple platform development, the question is when that future will arrive. This year the framework is debuting its third major release in iOS 15. How far has SwiftUI come, and is it ready for building serious apps?
I was very excited at this year’s WWDC when Apple announced DocC, their new “Documentation Compiler” tool that generates documentation from comments in your source code. Unfortunately, it’s not going to work for the majority of open source authors.
A few months ago, I shared my notes and resources for learning about compilers and LLVM. It turned out to be pretty popular and folks seemed to find it useful. So I decided to do it again, but this time for SwiftUI. However, unlike learning about compilers and LLVM, I am not declaring bankruptcy with learning SwiftUI. While I have still not written a single line of SwiftUI code, I know I eventually will.
Despite the fact that closures (and functions) are reference types in Swift, they cannot be compared using ==
or ===
. But why?
UserDefaults is one of the most misused APIs on Apple platforms. Specifically, most developers do not handle default values correctly. In fact, I have never worked on a single production codebase at a company where this was done accurately. Most libraries get it wrong, too.
I have a few Swift scripts to automate tedious tasks for maintaining my blog. I updated one today to use pipes. It took me a minute to figure out, because it did not feel very intuitive. I’m not sure if I feel that way because the interface is actually that clunky, or if I’m just inexperienced with Swift scripting. In any case, here’s how it works.
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.
As a brief follow-up to my previous post, I thought it would be helpful to enumerate the various types of “self” in Swift. It is an overloaded term. As we’ve seen, it can be quite confusing.
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.)
In today’s episode of Swift Unwrapped, JP and I had Jordan Rose on the show to discuss his recent blog posts on implementing the Swift runtime in Swift.
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.
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.
Swift’s strict initialization rules are great. They help prevent an entire category of bugs that were especially common in Objective-C. However, when working with Objective-C frameworks, particularly UIKit
, these rules can be frustrating.
JP and I released a special, off-schedule episode of Swift Unwrapped today. We welcomed Doug Gregor from the Swift Core Team back to the show to discuss the major new features coming in Swift 5.1.
Over a weekend recently I built a tiny Mac app (more on that later). What I was trying to achieve required executing AppleScript, like so many things on macOS. It seemed simple enough, but of course new app sandboxing restrictions in macOS Mojave got in the way.
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.
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.
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?
Swift Unwrapped recorded two episodes in the Podcast studio at WWDC this year. We had Greg Heo on to talk about our reactions to the announcements from the Keynote and Platforms State of the Union. Then we discussed Swift 4.2 and beyond with Ted Kremenek.
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.
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.
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.
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.
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.
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.
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
?
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?
There has been a ton of debate on the swift-evolution mailing lists about access control in Swift. A couple of days ago, the proposal SE-0159: Fix Private Access Levels was rejected. I want to share my thoughts on this, as well as thoughts on the larger story for access control in general. But first, let’s begin with a brief history of access control in Swift.
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!
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?
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!
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
.
I previously wrote about writing great documentation in Swift. If you haven’t read that post, head there now to catch up. This post is a follow-up with updates for GitHub’s new way to publish docs. This is how I’ve setup all of my Swift open source projects.
As you may know, I spoke at FrenchKit a couple of months ago. The organizers have been working hard to get all of the videos edited and uploaded, and my talk is now available here. 😄
You may have noticed that I did not write the last few issues of the Swift Weekly Brief. I took some much needed time off, and I was able to unplug and relax thanks to the wonderful JP Simard and Brian Gesiak. They took over for those weeks and I can’t thank them enough! Bas Broek also made regular contributions, which was super helpful.
I recently spoke at the FrenchKit conference about Swift Evolution. The talk, 140 proposals in 30 minutes, was originally intended to be an overview of the process and each of the proposals. However, as I was writing the talk, it evolved into something much more interesting. I ended up writing some code to analyze the proposals instead.
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.
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.
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.
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. 🤓
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.
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.
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.
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.
Earlier this month I had the incredible opportunity to speak at the try! Swift conference in Tokyo, Japan. 🇯🇵 It was such a fun and rewarding experience. A video of the talk is now online over at Realm’s blog, where it is synced with my slides. If you have not already seen it, go check it out!
A few weeks ago, I spoke at Realm in San Francisco at the Swift Language User Group (#SLUG) meetup. A video of the talk is now online over at Realm’s blog, where it is synced with my slides. If you haven’t already seen it, go check it out!
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.
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!
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!
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!
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!
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.
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.
Surprisingly, I have not seen anyone talking about what I just discovered in the iOS 9.0 API Diffs. (Well, actually what Max von Webel discovered.) There’s a hidden gem in the UIKit diffs. We no longer have to suffer through tracking down obscure bugs due to non-zeroing weak references.
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.
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.
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.
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.
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.
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.
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 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.1 — failable initializers.
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.
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.
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.
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.
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.