Swift Developer News - Hacking with Swift News, tips, and tutorials from Hacking with Swift https://www.hackingwithswift.com/articles/rss (c)2017 Paul Hudson https://www.hackingwithswift.com/favicon-96x96.png Swift Developer News - Hacking with Swift https://www.hackingwithswift.com/articles/rss Debugging Auto Layout feedback loops https://www.hackingwithswift.com/articles/59/debugging-auto-layout-feedback-loops https://www.hackingwithswift.com/articles/59/debugging-auto-layout-feedback-loops How to use UIViewLayoutFeedbackLoopDebuggingThreshold today Sun, 11 Mar 2018 16:35:58 +0000 A few days ago, Tyler Fox mentioned Auto Layout’s feedback loop debugger on Twitter, which was a feature announced back in WWDC 2016 but largely seems to have gone unnoticed since. Apple certainly weren’t trying to hide it – Marian Goldeen spent almost 15 minutes or so talking about it in this video – but with all the other big announcements coming at WWDC it’s easy for things to get lost.

Layout feedback loops don’t happen often, but you’ve almost certainly faced them at some point. They occur when your views are running their layout code, but part way through something triggers them to start their layout pass again. That might be the result of one view changing the size of one of its superviews, or perhaps because you have an ambiguous layout.

Either way, this problem manifests itself as your CPU maxing out and RAM usage steadily marching upwards, all because your views are running their layout code again and again without ever returning. Worse, if you try to debug the problem you’ll just see lots of layout code running – it’s not obvious where the loop is, or what might resolve it.

The Layout Feedback Loop Debugger is designed to solve this problem: you just set one of two launch arguments, depending on whether you want to target iOS/tvOS or macOS, then run your app as normal. Here’s how to try it out:

  1. Go to the Product menu, hold down Option, and choose “Run…”
  2. Select the Arguments tab, and click + to add a new entry
  3. For iOS apps enter -UIViewLayoutFeedbackLoopDebuggingThreshold 100
  4. For macOS apps enter -NSViewLayoutFeedbackLoopDebuggingThreshold 100

Although we’re using 100 above, you can use any number between 50 and 1000 – it represents how many times a view must layout its subviews in a single run loop before it is considered to be a feedback loop. So, by setting 100 we’re saying “allow one view to lay out itself 100 ...

We need to talk about Swift’s diversity problem https://www.hackingwithswift.com/articles/58/we-need-to-talk-about-swifts-diversity-problem https://www.hackingwithswift.com/articles/58/we-need-to-talk-about-swifts-diversity-problem There’s more to Swift than middle-aged white men Tue, 06 Mar 2018 12:25:08 +0000 It’s no secret that I love Swift: I’ve written over a dozen books about it, I speak at conferences around the world, and use it for all my own apps.

But as incredible as the language is, we as a community continue to have a deep-seated diversity problem, and we need to take more steps to address it. Just as importantly, Apple needs to take some steps to address it, because they are just as much part of the problem.

Swift was released as an open source project over two years ago, and Apple said this about Swift’s core team:

At project launch, the team is composed of Apple employees due to Swift’s origin within Apple. Over time, exceptional community members from a much more diverse background will be appointed based on their record of community involvement and contributions.

Back then the Swift core team was made up of Chris Lattner, Doug Gregor, Ted Kremenek, Joe Pamer, Joe Groff, John McCall, and Dave Abrahams – all men, all working for Apple. Things have changed a little today, but not in any meaningful way: Lattner now works at Google, Joe Pamer has left, and Ben Cohen has joined.

I have nothing against middle-aged white guys – I am a middle-aged white guy – but I don’t think anyone could argue that this constitutes “a much more diverse background.”

But the problem goes beyond just Apple. In the last few weeks I’ve been exchanging emails with the organizer of a well-known conference because I’m concerned that the speaker selection doesn’t reflect the diversity in our community. Their response has been positive: they acknowledge there’s a problem, and are keen to find ways to do better.

I spoke to [Ellen Shapiro](ht...

How Swift keypaths let us write more natural code https://www.hackingwithswift.com/articles/57/how-swift-keypaths-let-us-write-more-natural-code https://www.hackingwithswift.com/articles/57/how-swift-keypaths-let-us-write-more-natural-code Combine keypaths, associated types, and generics in one Mon, 26 Feb 2018 12:12:30 +0000 Swift 4.0 introduced new keypath types as part of SE-0161, but it’s fair to say a lot of folks either don’t understand them or don’t yet understand the benefits they can deliver.

Keypaths are designed to allow you to refer to properties without actually invoking them – you hold a reference to the property itself, rather than reading its value. Their use in Swift is still evolving, and in many ways they are influenced by keypath support in Objective-C, but already some clear design patterns are emerging.

I cover a selection of uses for Swift keypaths in my book Swift Design Patterns, but here I want to demonstrate how invaluable they are as a way of letting us reference different types in a natural way.

Try creating these two structs in your playground:

struct Person {
    var socialSecurityNumber: String
    var name: String

struct Book {
    var isbn: String
    var title: String

I’ve purposefully made them completely different so you can see how this pattern works.

Both Person and Book have an identifier that is unique: socialSecurityNumber and isbn respectively. If we wanted to be able to work with identifiable objects in general, we could try to write a protocol like this:

protocol Identifiable {
    var id: String { get set }

That would work well enough for Person and Book, but it would struggle for anything that didn’t store its identifier as a string – a WebPage might use a URL, and a File might use a UUID, for example.

Worse, it locks us into using id as the unique identifier for all our data, which isn’t a descriptive property name – you need to remember that id is actually a social security number for people and an ISBN for books.

Keypaths can help us solve this problem, allowing us to use them as adapters for very different data types – i.e., allow ...

Learn Swift for free with Swift in Sixty Seconds https://www.hackingwithswift.com/articles/56/learn-swift-for-free-with-swift-in-sixty-seconds https://www.hackingwithswift.com/articles/56/learn-swift-for-free-with-swift-in-sixty-seconds Master the fundamentals of Swift in bite-size chunks Tue, 20 Feb 2018 12:20:01 +0000 If you're the kind of person who likes learning new things quickly, I've just released the perfect Swift tutorial course for you: Swift in Sixty Seconds. This takes a "just the facts" approach to learn Swift, splitting the language up into 95 videos that teach precisely one Swift concept in just one minute or less.

Swift in Sixty Seconds is completely free to watch online, but there's also a download edition available for $10 that lets you enjoy the complete book and videos whenever and wherever you want.

Even though the videos are short and aimed squarely at beginners, a huge range of intermediate topics are covered, including:

  • inout parameters
  • Passing closures to functions
  • Class inheritance and deinitializers
  • Protocol extensions and protocol-oriented programming
  • Failable initializers
  • And more!

Swift in Sixty Seconds serves as a great introduction to the more advanced topics covered in my Pro Swift videos. So, if you're looking to get started with Swift today, Swift in Sixty Seconds might be just what you're looking for!

How to use Dynamic Member Lookup in Swift https://www.hackingwithswift.com/articles/55/how-to-use-dynamic-member-lookup-in-swift https://www.hackingwithswift.com/articles/55/how-to-use-dynamic-member-lookup-in-swift SE-0195 has been approved, so here’s a guide to get you started. Tue, 13 Feb 2018 18:33:17 +0000 Swift Evolution proposal SE-0195 is an attempt to bring Swift closer in behavior to scripting languages, but does so in a type-safe way – you don’t lose any of Swift’s safety, but you do gain the ability to write the kind of code you’re more likely to see in PHP and Python.

SE-0195 has been accepted after extensive review, and an implementation has already been written and submitted as a pull request. There’s a good chance it will be stable in time for Swift 5.0, but why wait?

In this article I want to walk you through the rationale for the change and provide code some samples showing how it works. If you’re short on time, the TL;DR version is that this change will help dynamic languages such as Python be used much more easily from Swift code, similar to the way we can already call into Objective-C.

Why change?

There are lots of words you could use to describe Swift, but I think “safe” is probably the one that comes to mind first for many people – strong type safety, optionality, throwing functions, and more all combine to make it harder to make mistakes in Swift.

On the other end of the spectrum, languages such as PHP, Python, and JavaScript are more relaxed about safety. That doesn’t mean they encourage bad code (you can write bad code in any language), just that they require developers to keep more information in their head while working.

You might think these two worlds can’t easily be reconciled, but SE-0195 takes a good stab at it. At its core is a new attribute called @dynamicMemberLookup, which instructs Swift to call a subscript method when accessing properties. This subscript method, subscript(dynamicMember:), is required: you’ll get passed the string name of the property that was requested, and can return any value you like.

Let’s look at a trivial example ...

Expanding the Swift Knowledge Base https://www.hackingwithswift.com/articles/54/expanding-the-swift-knowledge-base https://www.hackingwithswift.com/articles/54/expanding-the-swift-knowledge-base If you’re looking for Swift tips and tricks, the best is getting better. Mon, 12 Feb 2018 08:51:39 +0000 I've just added 270 articles to my Swift Knowledge Base, taking it up to 576 tips, techniques, and answers for Swift developers – all updated for the latest version of Xcode and Swift. Click here to browse the knowledge base by category or search for something specific.

Many people have never heard of my work on this knowledge base, mostly because I'm terrible at marketing. If you find something useful here, please help pass on the word by telling others!

I've included a full list of all 270 new articles below, but here are my top twelve you should check out:

  1. How to send notifications asynchronously using NotificationQueue
  2. How to use an image for your background color with UIColor(patternImage:)
  3. How to add a custom initializer to a struct without losing its memberwise initializer
  4. How to lock Interface Builder controls to stop accidental changes
  5. How to generate shaped random numbers using GKGaussianDistribution
  6. How to find an aspect fit image’s size inside an image view
  7. How to group arrays using dictionaries
  8. How to read the battery level of an iPhone or iPad
  9. How to check whether a date is inside a date range
  10. [How to display different strings based on available space usi...
Review: Flawless App https://www.hackingwithswift.com/articles/53/review-flawless-app https://www.hackingwithswift.com/articles/53/review-flawless-app If you want pixel-perfect designs, this is the app for you. Thu, 08 Feb 2018 12:14:12 +0000 Flawless App is an app with precisely one purpose: to make it easy for developers everywhere to make pixel-perfect layouts. It does this using an ingenious iOS Simulator injection to overlay images from your designers over your live application, so you can see the designs and your actual layouts side by side.

It’s important to stress up front that Flawless App does not modify your code or go near your final app, so there’s no performance degradation or chance things will go wrong for your users. Instead, it’s controlled by a small macOS menu bar app backed up by the simulator overlay – it’s the kind of thing you can leave running all the time if you wanted.

To get started, drag an image onto the Flawless App icon to have it loaded into your simulator. It supports JPEG, PNG, GIF, TIFF, and even Sketch files so you should be able to find something that works for you. That image then gets loaded into an overlay alongside your app, at which point you have three viewing options:

  • Just show your app. This lets you use the app like normal, so you can navigate to whichever screen you’re investigating.
  • Overlay, which shows both your app’s layout and the design image on top of each other, with an alpha slider letting you control how much of the design should be visible.
  • Split-screen, which puts a draggable divider onto the screen, letting you move between your design and the current app.

It’s hard to overstate how useful the split-screen mode is – you can see both your current layout and your target layout side by side, making it extremely convenient to see where you need to make changes. Flawless App can even output an animated GIF for you, making it easy to show others the current state of your work.

And that’s the entire app. It’s not trying to throw in lots of features, and it’s not trying to solve multiple different problems – it’s designed to do one thing, and ...

Swift 4.1 improves Codable with keyDecodingStrategy https://www.hackingwithswift.com/articles/52/swift-4-1-improves-codable-with-keydecodingstrategy https://www.hackingwithswift.com/articles/52/swift-4-1-improves-codable-with-keydecodingstrategy Snake case is now just a few keystrokes away. Mon, 05 Feb 2018 10:31:54 +0000 Swift 4.0 brought many great new features, including multi-line strings, better keypaths, and lots of improved dictionary functionality. But it also gave us Codable for the first time: by far the easiest, safest way to convert Swift objects into JSON and XML.

However, Codable had one particular annoyance that hit most users: if your JSON used snake_case for its key names and your Swift code used camelCase for its property names, Codable wouldn’t be able to convert between the two – you needed to create your own CodingKeys mapping to explain how the two matched up.

Well, Swift 4.1 has fixed this beautifully: along with awesome new features of its own there’s a new keyDecodingStrategy property on JSONDecoder that can automatically convert between snake_case and camelCase if you need it. The inverse property, keyEncodingStrategy, also exists on JSONEncoder so you can convert your Swift camelCase names back into snake_case.

Enough chat – let’s look at a practical example. Create a new Playground and give it this JSON string:

let jsonString = """
        "name": "MacBook Pro",
        "screen_size": 15,
        "cpu_count": 4
        "name": "iMac Pro",
        "screen_size": 27,
        "cpu_count": 18

let jsonData = Data(jsonString.utf8)

That stores an array of two items, each describing a Mac. As you can see, both screen_size and cpu_count use snake case – words are all lowercased, with underscores separating them. I’ve added a conversion to Data at the end, because that’s what JSONDecoder works with.

Now, we want to convert that JSON into an array of Mac instances using this struct:

struct Mac: Codable {
    var name: String
    var screenSize: Int
    var cpuCount: Int

That follows standard Swift naming conventions, so the property names are all camelCased ?...

Conference report: dotSwift 2018 https://www.hackingwithswift.com/articles/51/conference-report-dotswift-2018 https://www.hackingwithswift.com/articles/51/conference-report-dotswift-2018 France's largest iOS conference was back in Paris and better than ever Tue, 30 Jan 2018 14:07:58 +0000 There are lots of iOS conferences, but none are quite like dotSwift. The 2018 edition took place yesterday, and included all the hallmarks it’s famous for: spectacular venues, short and snappy talks, impeccable organization, and complete focus on speakers.

If you haven’t attended dotSwift before (it was my first time!), you need to start by understanding the conference is always held in theaters or similar locations – think plush seats, boxes, and a huge and well-lit stage. Unlike almost every other coding conference around, attendees are requested to close their laptops and turn off their phones. As a result, no one sits at the back chatting on Slack; everyone is focused on learning something new.

This year’s speakers included Ben Cohen, Brandon Kase, Graham Lee, Ben Scheirman, Ellen Shapiro, Sally Shepard, and myself, covering topics such as coordinators, protocol extensions, and functional programming. Each talk followed the same structure seen at TED conferences: everyone is limited to 18 minutes, so there’s no chance to go off on tangents. After each talk, Daniel Steinberg – the guest emcee at dotSwift – sat down with the speaker and asked a variety of questions to go into more detail on specific topics. Very few conferences do this, but I think it gave everyone a chance to get to know each speaker better. Perhaps next year attendees could submit questions ahead of time?

All the talks had their own merits (I even demonstrated my flawless Franglais in mine!), but Ben Cohen’s deserves particular mention. Apple has recently adopted a much more open policy, including sending developers like Ben – who works on the standard library at Cupertino – to Swift conferences around the world. This is no small step for a company steeped in secrecy, but with Swift being an open source project they are keen to be a part of the community just like everyone else.

Alongside the main speakers were a handful of lightning talks lasting just four (yes, four) minutes. Several folks spoke about top...

What’s new in Swift 4.1 https://www.hackingwithswift.com/articles/50/whats-new-in-swift-4-1 https://www.hackingwithswift.com/articles/50/whats-new-in-swift-4-1 Synthesized equatable, conditional conformance, and more! Wed, 24 Jan 2018 19:54:15 +0000 Apple released the first beta of Xcode 9.3, bringing with it the first release of Swift 4.1 alongside new APIs targeting iOS 11.3. This first point release of Swift 4 brings with it some useful improvements, and if you’re keen to get ahead of the game you can give them a try today.

Start by installing Xcode 9.3 then create a new playground. Let’s take a look at the top three new features for this release…

Synthesized Equatable and Hashable

The Equatable protocol allows Swift to compare one instance of a type against another. When we say 5 == 5, Swift understands what that means because Int conforms to Equatable, which means it implements a function describing what == means for two instances of Int.

Implementing Equatable in our own value types allows them to work like Swift’s strings, arrays, numbers, and more, and it’s usually a good idea to make your structs conform to Equatable just so they fit the concept of value types better.

However, implementing Equatable can be annoying. Consider this code:

struct Person {
    var firstName: String
    var middleName: String
    var age: Int
    var city: String

If you have two instances of Person and want to make sure they are identical, you need to compare all four properties, like this:

struct Person: Equatable {
    var firstName: String
    var lastName: String
    var age: Int
    var city: String

    static func ==(lhs: Person, rhs: Person) -> Bool {
        return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.age == rhs.age && lhs.city == rhs.city

Even reading that is tiring, never mind writing it.

Fortunately, Swift 4.1 can synthesize conformance for Equatable – it can generate an == method automatically, which will compare all properties in one value with all properties in another, just like above. So, all you have to do now is add `...

Swift Coding Challenge 2: how can this condition work? https://www.hackingwithswift.com/articles/49/swift-coding-challenge-2-how-can-this-condition-work https://www.hackingwithswift.com/articles/49/swift-coding-challenge-2-how-can-this-condition-work Put your Swift skills to the test and learn something new. Tue, 23 Jan 2018 18:19:00 +0000 Previously I posted a Swift coding challenge that seemed simple at first, but of course took a little more thinking. These sorts of challenges are fun not because you’ll write perfect code (often the opposite!) but because they force you to think about how the language works and perhaps learn something along the way.

This weekend I tweeted out another challenge, and had some excellent responses. Now that my followers have had a chance to solve it themselves, it’s time to take a closer look at the problem and the various solutions.

The challenge

Create a new Swift playground then give it this code:

if a == 1 && a == 2 && a == 3 {
    print("All three match!")

How many ways can you make “All three match!” be printed?

Solution 1: Operator overloading

Swift allows you to create your own operators freely, but it also allows you to modify existing operators however you want. In this case we’re looking at two operators: == and &&. If we replace the default definition of either of them our condition will evaluate as true.

First let’s look at ==, because that’s the easier of the two. This just checks for equality between the integer on its left-hand side and the integer on its right-hand side, so we can rewrite == so that it always returns true. That is, given any two numbers, we can tell Swift they are equal.

Here’s how that approach looks:

extension Int {
    static func ==(lhs: Int, rhs: Int) -> Bool {
        return true

// a can now be any integer
let a = 9

That will of course break all the other uses of == you have in your app, so if you wanted to keep the rest of your code intact you could overload == where the left-hand side is a string and the right-hand side is an integer, like this:

func ==(lhs: String, rhs: Int) -> Bool {
    return true


Top Swift and iOS Conferences in 2018 https://www.hackingwithswift.com/articles/48/top-swift-and-ios-conferences-in-2018 https://www.hackingwithswift.com/articles/48/top-swift-and-ios-conferences-in-2018 Find the best iOS conference near you! Thu, 18 Jan 2018 17:16:16 +0000 Conferences are always a great way to discover new techniques, be inspired by great talks, and meet like-minded developers. Fortunately, there are some amazing conferences taking place around the world this year, so no matter where you are you should be able to go along and learn something new.

Full disclosure: I’m speaking at several of these, including dotSwift, iOSCon, AppDevCon, and iOSDevUK. If you’d like me to speak at your conference just get in touch.


January 29th, Paris, France (Link)

dotSwift has a strikingly unusual structure: everyone closes their laptops, the lights are dimmed, and all the focus is on the speaker. Plus, talks are kept to just 18 minutes, and not announced in advance – when you sit down you have no idea what’s coming next.


February 15th-16th, Cluj Napoca, Romania (Link)

Taking place in Transylvania (known for being one of the most beautiful places in Europe as well as at least one other thing…), MobOS is now in its fifth year. The theme this year is “mobile community building and sharing,” and it has attracted speakers from as far away as Japan!

try! Swift Tokyo

March 1st-3rd, Tokyo, Japan (Link)

try! Swift Tokyo runs across three action-packed days, with the third day being entirely devoted to labs and workshops. This year’s speaker list is as good as always, featuring well-known faces such as Wendy Lu, Samuel Goodwin, and Javier Soto, alongside homegrown talent like Katsumi Kishikawa and Shuichi Tsutsumi.

Teki Con

March 12th-14th, Atlanta, USA (Link)

This is a new entry into the iOS conference space, and they are starting with a bang: an epic conference space, hands-on labs, and a fantastic speaker line up. How fantastic? Well, there’s Peter Steinberger, Soroush Khanlou, and Sommer Panage just to name a few – it?...

Write your scripts in Swift with Beak https://www.hackingwithswift.com/articles/47/write-your-scripts-in-swift-with-beak https://www.hackingwithswift.com/articles/47/write-your-scripts-in-swift-with-beak It’s a smart and simple way to run code by function. Mon, 08 Jan 2018 13:20:42 +0000 If you’re visiting here it’s because you’re already sold on Swift as a great language for apps, but have you ever considered using it for scripting? If not, a new GitHub project from Yonas Kolb is here to convince you otherwise: it’s called Beak and it lets your run Swift code straight from the command line.

To get started, run these three commands from your Mac’s terminal:

git clone https://github.com/yonaskolb/Beak.git
cd Beak
swift run beak run install

That builds and installs Beak, which means it’s ready to run any Swift scripts you need.

Let’s try it out now. Create a new Swift file on your desktop called factors.swift and give it this content:

import Foundation

public func calculate() {
    let number = 100
    let factors = (1...number).filter { number % $0 == 0 }
    print(factors.reduce("Factors: ") { $0 + String($1) + " " })

That creates a single function called calculate(), which creates an array of numbers that divide equally into 100, then prints them out as a single string.

To run that using Beak you need to write a command that does the following:

  • Specifies factors.swift as its input filename.
  • Tells it to run a single function from the file.
  • Provides the function name to run.

Run this command now:

beak --path factors.swift run calculate

You specify the function name you want to run, so a single Swift script can contain as many related functions as you want.

As well as run you can also use list to show the list of available functions:

beak --path factors.swift list

That will show you there’s only function available, which is our calculate() function.

Tip: Beak can only see functions that are marked as public. If you want a function for internal use only – i.e., not exposed by the list command – just don’t declare it as public.

Right now our function uses a hard-coded input val...

Take the Hacking with Swift 2017 Swiftmas Quiz https://www.hackingwithswift.com/articles/46/take-the-hacking-with-swift-2017-swiftmas-quiz https://www.hackingwithswift.com/articles/46/take-the-hacking-with-swift-2017-swiftmas-quiz 16 questions that will test your knowledge of Swift history and more Fri, 15 Dec 2017 12:14:32 +0000 I'm supposed to be busy finishing my new book on Server-Side Swift with Vapor, but it's the Swiftmas season and I thought you all deserved some time away from Xcode. I already posted a special Swiftmas wordsearch but you're all far too clever and solved that within a day.

So, it's time for something harder: Hacking with Swift's first annual Swiftmas Quiz. Below you'll find 16 questions that test your knowledge of Swift's history, Swift's community, and Swift's canine friends. Share your result on Twitter and see if you beat your friends!