turing complete with a stack of 0xdeadbeef

Writing by tag: swift

Swift protocol requirement quirks

17 January 2024

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!

Continue…

Swift URL absoluteString versus path

17 August 2023

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.

Continue…

Using DocC on GitHub Pages

Pros and Cons 22 April 2022
Updated: 25 April 2022

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.

Continue…

When should you use Decimal instead of Double?

01 February 2022

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?

Continue…

First impressions of SwiftUI

12 November 2021

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.

Continue…

Deprecating PresenterKit

06 November 2021

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.

Continue…

Different ways to observe properties in Swift

08 August 2021

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.

Continue…

Is SwiftUI ready?

01 July 2021
Updated: 08 October 2021

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?

Continue…

Resources for learning SwiftUI

07 April 2021

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.

Continue…

Using pipes in Swift scripts

18 March 2021
Updated: 22 March 2021

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.

Continue…

Resources for learning about compilers and LLVM

28 December 2020

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.

Continue…

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

The answer might surprise you 22 December 2020
Updated: 02 March 2022

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.)

Continue…

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

08 October 2020

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.

Continue…

Swift globals and static members are atomic and lazily computed

16 July 2020

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.

Continue…

Debugging a subtle Swift bug that will make you facepalm

07 November 2018

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.

Continue…

Swift tip: Building arrays with compactMap

29 July 2018

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.

Continue…

Swift's new calling convention

From callee-owned to guaranteed 05 July 2018

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?

Continue…

Thoughts on WWDC 2018

Community over technology 11 June 2018

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.

Continue…

Why optional closures in Swift are escaping

10 June 2018

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.

Continue…

Ending the Swift Weekly Brief

Taking an indefinite hiatus from writing the newsletter, and looking for a new owner 28 December 2017
Updated: 08 February 2018

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.

Continue…

Floating-point Swift, ulp, and epsilon

Exploring floating-point precision 01 October 2017
Updated: 03 April 2023

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.

Continue…

Measuring Swift compile times in Xcode 9

Using -Xfrontend Swift compiler flags 18 September 2017

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.

Continue…

A story about Swift source compatibility

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

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.

Continue…

Protocol composition in Swift and Objective-C

Designing optional semantics without optional methods 05 June 2017

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?

Continue…

Writing better singletons in Swift

Avoiding common pitfalls 04 June 2017

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?

Continue…

Swift Unwrapped

Co-hosting a new podcast with JP Simard 07 March 2017

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!

Continue…

Refactoring singleton usage in Swift

Tips for a cleaner, modular, and testable codebase 10 February 2017

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?

Continue…

Pushing the limits of protocol-oriented programming

Talk at Swift Summit in San Francisco 23 January 2017

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!

Continue…

Testing and mocking without OCMock

For Swift and Objective-C 16 January 2017

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.

Continue…

Shipping Swift 3.0

An update on my open source libraries 01 October 2016

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.

Continue…

Speaking at FrenchKit

Paris, France 30 September 2016

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.

Continue…

Enums as configuration: the anti-pattern

Implementing the open/closed principle 31 July 2016

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.

Continue…

Migrating to Swift 3

Advice, tips, and warnings 25 July 2016

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. 🤓

Continue…

Swift 3 sherlocked my library

Many of our "Swifty" wrappers are no longer necessary 03 July 2016

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.

Continue…

Avoiding the overuse of @objc in Swift

Don't let Objective-C cramp your style 04 June 2016

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.

Continue…

Open source everything

Getting meaningful contributions to move your projects forward 22 May 2016

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.

Continue…

Swift documentation

Writing, generating, and publishing great docs in Swift 20 May 2016
Updated: 18 April 2018

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.

Continue…

The new weekly brief

The Swift Weekly Brief gets a new home 14 January 2016

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.

Continue…

Open source Swift: weekly brief #4

What's been happening on Swift.org? 07 January 2016

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!

Continue…

Open source Swift: weekly brief #3

What's been happening on Swift.org? 24 December 2015

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!

Continue…

Open source Swift: weekly brief #2

What's been happening on Swift.org? 17 December 2015

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!

Continue…

Open source Swift: weekly brief

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

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!

Continue…

Swift open source

Let the revolution begin 06 December 2015

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.

Continue…

Building type-safe, composable data sources in Swift

A modern approach to collection views and table views 25 October 2015

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.

Continue…

Swift enumerations and equatable

Implementing equatable for enums with associated values 26 July 2015
Updated: 03 January 2021

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.

Continue…

Namespaced constants in Swift

Using nested types for clarity 19 July 2015
Updated: 23 July 2015

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.

Continue…

Using Core Data in Swift

Talk at Realm in San Francisco 25 May 2015

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.

Continue…

Failable initializers, revisited

Functional approaches to avoid Swift's failable initializers 06 April 2015

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.

Continue…

Functional notifications

Exploring the flexibility of Swift micro-libraries 31 March 2015

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.

Continue…

Better Core Data models in Swift

How Swift can bring clarity and safety to your managed objects 17 February 2015

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.

Continue…

Swift, Core Data, and unit testing

Working around Swift's constraints to unit test models 05 January 2015

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.

Continue…

Swift failable initializers

When failable becomes fallible, and how to avoid it 22 October 2014

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.

Continue…

Adaptive user interfaces

Exploring iOS size classes and trait collections 01 October 2014

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.

Continue…

Apples to apples, Part III

A modest proposal: can Swift outperform plain C? 21 August 2014

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.

Continue…

On the value of benchmarks

A brief examination of measuring code performance 19 August 2014

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.

Continue…

Apples to apples, Part II

An analysis of sorts between Objective-C and Swift 06 August 2014

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.

Continue…

Apples to apples

A comparison of sorts between Objective-C and Swift 25 June 2014
Updated: 01 August 2014

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.

Continue…