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 $5000 of Swift books must be won! https://www.hackingwithswift.com/articles/35/5000-of-swift-books-must-be-won https://www.hackingwithswift.com/articles/35/5000-of-swift-books-must-be-won Find out how you can win free books and videos to learn Swift faster! Mon, 23 Oct 2017 13:00:40 +0000 In the last month I updated all 11 of my Swift books for Swift 4, and released an all-new book called Dive Into SpriteKit that teaches games programming in an incredible new format.

Of course, I want to celebrate all this in style, which is why I’m giving away over $5000 of Swift books and videos to lucky readers – read on to find out how!

All books updated for Swift 4

Every one of my Swift books was updated for Swift 4 last month, and thanks to my lifetime update policy the updates were completely free for existing readers.

Of course, just doing simple version updates isn’t much fun, so I took the opportunity to add extra content – new language features in Pro Swift, new workout features in watchOS, new iPhone X compatibility in Hacking with Swift, and more.

Readers tell me that my lifetime update policy – along with the bonus content they get from my Frequent Flyer Club – is a key reason they choose Hacking with Swift books over others, and it’s such a great feeling when I see readers finishing one book then coming back for more.

All my books are covered by my lifetime update policy, which means they all get free updates for Swift 5, 6, and beyond – it’s the perfect way to protect your learning investment!

All my books are priced as low as possible, but you can save even more money ...

Before and after: how to refactor your Swift code https://www.hackingwithswift.com/articles/34/before-and-after-how-to-refactor-your-swift-code https://www.hackingwithswift.com/articles/34/before-and-after-how-to-refactor-your-swift-code Can the worst possible code ever get cleaned up? Apparently so! Sun, 22 Oct 2017 20:25:58 +0000 Matt Gallagher has written a thoroughly brilliant piece showing off terrible application architecture and (more importantly) how to refactor it to be sensible. He starts with a scenario that you may already be painfully familiar with: no model separation, meaning that the data required for his app to work must be juggled between views and view controllers.

This in itself is sadly not uncommon, but to really drive his point home Gallagher ported some 20-year-old macOS code to an iOS app, to produce Mines for iOS – a Minesweeper clone that might look good enough to players, but was a festering vortex of appalling code underneath.

How bad? Well, to give you a taste:

Each of the SquareView objects (instances of UIButton) which represent the tiles in the game contains the following properties… This is not a cached representation of state store in another location, this is the only representation of the minefield, spread across the 100 different UIButton subclass instances used to display the minefield.

Now, anyone can write bad code – myself included! – but Gallagher's article is only just getting started, because his whole point is that even something this shocking can be refactored into a more modern, sensible layout. Even better, his GitHub repository provides before and after versions of the code so you can see for yourself what changed and why.

Towards the end the article discusses the whole point of separating your model, and that's where it gets really interesting:

Writing an application without a separated Model is considered the worst application design, not because it immediately leads to disaster but because it indicates that you’ve never tried to clearly isolate what your program does. We don’t write applications because we love constructing views and controllers – the...

Sharpshooter: debugging for lazy people https://www.hackingwithswift.com/articles/33/sharpshooter-debugging-for-lazy-people https://www.hackingwithswift.com/articles/33/sharpshooter-debugging-for-lazy-people If you think print() is a great way to debug your code, this is the perfect Xcode extension Fri, 20 Oct 2017 07:05:30 +0000 There are lots of ways of debugging programs, but probably the first one we all learn is writing print() statements everywhere in our code. This simple approach makes it easy to follow program flow: functionA() got called first, then functionB(), then evilCrashFunction(), and boom – you've found what causes the problem.

Despite this approach being primitive at best, it tends to stick simply because it was the first thing we learned, so even experienced developers have been known to scatter some print() calls around to figure out what's going on.

Well, if this is your preferred approach – or if you know a "friend" who works like this – I wrote a new Xcode extension that will help. It's called Sharpshooter, and it lets you add or remove print() statements to your function entry points in just one click.

Here’s an example of code before adding comments:

class BrokenStuff {
    func broken() {
        print("<Silent screaming>")

    private func reallyBroken() {

    static private func superBroken() {
        print("<Silent screaming *and* tears>")

And after:

class BrokenStuff {
    func broken() {
        print("# Sharpshooter: Entering broken()")
        print("<Silent screaming>")

    private func reallyBroken() {
        print("# Sharpshooter: Entering reallyBroken()")

    static private func superBroken() {
        print("# Sharpshooter: Entering superBroken()")
        print("<Silent screaming and tears>")

In case you were wondering, the name comes from a joke about a Texan sharpshooter who fires gunshots at the door of a barn, then draws a target around the biggest cluster of hits and claims to be a sharpshooter – a pretty accurate analogy for finding bugs using print(), I think.

**Link: [Sharp...

Lumina is the instant Core ML video framework you're looking for https://www.hackingwithswift.com/articles/32/lumina-is-the-instant-core-ml-video-framework-you-re-looking-for https://www.hackingwithswift.com/articles/32/lumina-is-the-instant-core-ml-video-framework-you-re-looking-for Want Core ML? Want video? Lumina puts the two together. Wed, 18 Oct 2017 14:35:12 +0000 The Core ML and Vision frameworks are two of the most impressively powerful additions in iOS 11, but they are also two of the most complex – there's a big learning curve to get even basic applications working, and that can be off-putting for newcomers. While one option is to buy a good book (gratuitous plug), another is just to dive in with some code, and that's where David Okun's new Lumina framework comes in.

Lumina is like hitting hyperspace for your ML idea: it gets rid of all the AVFoundation heavy lifting that's required to get off the ground, replaces tricky image formats like CVImageBuffer with standard types like UIImage, and provides recognition for common data types such as QR codes, barcodes, and faces. But where Lumina goes from "neat" to "awesome" is that it comes with Core ML built in for devices running iOS 11 or later: provide it with any Core ML-compatible model and have it stream predictions directly to your delegate as they come in from the camera.

All the magic is done using a single LuminaViewController that you configure and present. Should it stream frames or deliver them on completion? Which camera do you want to use? Do you need maximum quality or can you sacrifice quality for speed? Should the user be allowed to zoom, and by how much? And of course the important one: which Core ML model should it use for predicting the contents of the camera feed?

You can do all this yourself – of course you can – but why would you when Lumina does all the hard work for you? By removing most if not all of the barriers from entry into the world of Core ML and Vision apps, I'm hopeful projects like Lumina will open this fascinating new area of development to more people.

Link: Lumina.

Conference report: Pragma 2017 https://www.hackingwithswift.com/articles/31/conference-report-pragma-2017 https://www.hackingwithswift.com/articles/31/conference-report-pragma-2017 The Italian conference is fast becoming the European conference Sat, 14 Oct 2017 08:10:09 +0000 I'm just returning from Verona, Italy, where I was attending #Pragma conference – already Italy’s biggest conference for Apple developers, and certainly challenging to be in the top three across Europe as a whole.

This year’s event saw a first-class roster of speakers such as Soroush Khanlou, Cate Huston, Daniel Steinberg, and Felix Krause, so it was no surprise that the talks were as much inspiring as they were informative. I particularly enjoyed John Sundell’s talk “Game Programming for App Developers”, where he announced his new Imagine Engine for game development, but equally memorable was Soroush Khanlou’s talk “You Deserve Nice Things” – not least because prosecco was served part-way through.

My own talk was on the importance of using Instruments, but I also ran a full-day macOS coding workshop alongside workshops from Daniel Steinberg and Tanner Nelson.

With such a packed schedule – each day’s talks finished at 6:45! – it was impressive that the organizers were able to keep everything running smoothly. Apart from a handful of inevitable projector gremlins, everything was perfectly polished.

Pragma is a non-profit event that offers generous discounts for students, so it’s great to see them growing year-on-year. This year’s event actually sold out, so I guess next year it will be a bigger venue – hopefully somewhere that can match the beauty of Verona. It’s also great to see a published code of conduct that was re-iterated during the opening keynote – the atmosphere was consistently positive, friendly, and welcoming, with lots of chances to mingle with other developers and meet new people.

Ultimately, any conference survives or dies based on the people that attend, and I think this is where Pragma shines brightest. Yes, this is a conference that bills itself as “the Italian conference”, but only 40% of attendees were...

Linex is an Xcode extension you might actually install https://www.hackingwithswift.com/articles/30/linex-is-an-xcode-extension-you-might-actually-install https://www.hackingwithswift.com/articles/30/linex-is-an-xcode-extension-you-might-actually-install Xcode extensions can't do much, but this one stands out. Fri, 13 Oct 2017 14:51:31 +0000 Xcode extensions were introduced in Xcode 8, but have seen limited use because there are so many restrictions – you can read some text, modify it, and send some text back, but that’s about it.

Even with those restrictions, Kaunteya Suryawanshi has managed to build something that’s actually quite useful, which is no easy feat. His new extension is called Linex, and comes with a selection of text-editing features to help you do more with your keyboard:

  • Duplicating and deleting lines.
  • Duplicating line with comment – great for trying something out without losing your existing code.
  • Joining lines together.
  • Aligning property definitions.
  • Adjusting common values, e.g. false to true or incrementing and decrementing numbers.

Having better source editor extensions was on my Xcode wish list, but until then give Linex a try.

Link: Linex.

Why many developers prefer Swift to Objective-C https://www.hackingwithswift.com/articles/29/why-many-developers-prefer-swift-to-objective-c https://www.hackingwithswift.com/articles/29/why-many-developers-prefer-swift-to-objective-c Generics, protocols, and optionals come out on top Wed, 11 Oct 2017 21:00:21 +0000 Last week I published an article where developers outlined some of the reasons they prefer Objective-C in a world where Swift is increasingly dominant.

It won’t surprise you to learn that the article generated a huge amount of discussion (which is no bad thing!), including a great many people getting in touch asking to present the opposing case: why they switched from Objective-C to Swift and are loving it.

I received many responses from a wide range of developers, so strap yourself in – this is going to be long!

What made you move to Swift in the first place?

Aleksandar Vacic: Curiosity mostly, but I did not jump immediately on it. Only with 3.0 after the Big Rename and the promise of future source compatibility. This was crucial to be eligible for client projects.

Harlan Haskins: I’m not ashamed to admit it was the shininess and the ensuing hype train. Swift came out while I was an intern on the Wireless Software Engineering team at Apple and I started using it from 1.0 beta 1. I battled my fair share of skepticism that wasn’t entirely unwarranted, and after using Swift in personal projects later, I never looked back.

Louis D'hauwe: Back in June 2014, when the first beta of Swift came out, I took a quick look at the language to see what the hype was about. I didn’t actually write a decent project in Swift until 2015 with the Swift 1.2 release. The main reason I wrote that project in Swift is because I was in college and wanted to learn a new language. In the summer of 2015 I started working full time as an iOS developer and ever since I’ve been writing new projects in Swift.

Lucas Farah: When Apple first launched it, I saw that it was going to be the future of iOS development, so I decided to learn and start coding in the early days because I’d have to update my projects to Swift later anyways.

Josh Adams: I changed my profession in mid-2015 from lawyer to iOS developer. I may...

Designing apps for the iPhone X notch https://www.hackingwithswift.com/articles/28/designing-apps-for-the-iphone-x-notch https://www.hackingwithswift.com/articles/28/designing-apps-for-the-iphone-x-notch Get it right and it looks great. Get it wrong, and, well... Thu, 05 Oct 2017 23:17:49 +0000 A number of people have written blog posts about the new sensor housing in iPhone X, but Max Rudberg has published the best yet in his article UI Design for iPhone X: Top Elements and the Notch.

Not only does Rudberg walk us through the key parts of Apple’s design guidelines for iPhone X, but he gives hands-on examples of how various components can look and work alongside the sensor housing. So, for the navigation bar he compares translucent bars, transparent bars, and a card-like approach as seen in Apple Music.

There’s a lot of fine-grained detail to absorb before you start updating your apps for iPhone X, but I really recommend you pay close attention to his discussion of alignment in landscape mode – it’s harder than it looks!

If you’re short on time, here’s a quote that sums it up nicely:

Eventually, they will get rid of the notch. It could be 2, 5, or even 10 years, but it’s a stop gap, not a permanent design solution. In the meantime, treat it like the elephant in the room. We all know it’s there, but for the most part, you should design as if it’s not.

Link: UI Design for iPhone X: Top Elements and the Notch

Why many developers still prefer Objective-C to Swift https://www.hackingwithswift.com/articles/27/why-many-developers-still-prefer-objective-c-to-swift https://www.hackingwithswift.com/articles/27/why-many-developers-still-prefer-objective-c-to-swift Lack of ABI stability, slow compile times, poor Xcode support, and more hold Swift back Wed, 04 Oct 2017 20:59:15 +0000 For several years after the iOS SDK was announced, developers were flocking to Objective-C as they sought to get their slice of the app development gold rush. But those times are gone: Swift has been with us for over three years now, and has largely pushed its older sibling from the limelight.

Objective-C – once the rising star of the app development world – has started to become a second-class citizen in the Apple ecosystem. Yes, it might occasionally get dusted off for a slide or two at WWDC, but the majority of conference talks worldwide are in Swift, Apple is pushing Swift hard in the education space, and major language features come to Swift first.

But if you’re still using Objective-C, you’re not alone – many other developers still prefer Objective-C to Swift, and with good reasons. I got in touch with some Objective-C developers to ask what’s holding them back, whether they feel Objective-C development has become stigmatized, and more – here’s what they had to say…

Note: Views expressed here are personal and may not represent the views of their employers; people are listed in the order they responded; some answers were edited for length.

What are the main reasons holding you back from switching to Swift as your primary language?

Steve Troughton-Smith: There are a variety of reasons why I avoid Swift. First and foremost, I don't enjoy using it – I find the language much more difficult to read and parse than ObjC, especially with if-let variable assignment in loops and switch statements (which is chaotically overused in Apple's body of sample code, like for ARKit). I am no newcomer to different languages, having written things for all kinds of platforms, and Swift is definitely at the extreme low end of the legibility spectrum for me.

I'm not yet convinced of Apple's level of participation in the language — four years on, Swift is not used for important pieces of iOS, OS or frameworks (I maintain a running list of Swift apps from Apple on Twitter, an...

Stop what you’re doing and watch these awesome NSSpain videos https://www.hackingwithswift.com/articles/26/stop-what-you-re-doing-and-watch-these-awesome-nsspain-videos https://www.hackingwithswift.com/articles/26/stop-what-you-re-doing-and-watch-these-awesome-nsspain-videos 26 sessions on testing, GameplayKit, accessibility and more. Tue, 03 Oct 2017 18:34:23 +0000 NSSpain took place just over two weeks ago in Logroño, Spain, and although I wasn’t lucky enough to be able to attend we are all lucky enough that the organizers have managed to get a huge collection of session videos online. Sometimes these can take months to appear, so it’s great to see NSSpain bucking the trend!

I’ve only had time to watch a handful, but there were so many great sessions that it will probably take me a couple of weeks to get through them all. If you’re keen to learn something new today – and who isn’t? – here are direct links to videos for the talks:

Full-day Swift workshops at Hacking with Swift Live https://www.hackingwithswift.com/articles/25/full-day-swift-workshops-at-hacking-with-swift-live https://www.hackingwithswift.com/articles/25/full-day-swift-workshops-at-hacking-with-swift-live Come to my online webinar series and take your Swift to the next level! Mon, 02 Oct 2017 12:20:39 +0000 Hacking with Swift Live is a day-long online workshop series that will help you take your Swift skills to the next level. Because it takes place entirely online, you can watch from anywhere in the world, and you get access to the recorded sessions so you can re-watch as often as you need.

There are four workshops taking place, each made up of six hour-long sessions plus time for questions and breaks. So, regardless which event you attend, you’ll get at least six hours of hands-on Swift instruction.

The list of sessions depends which workshop you want to attend – there are two on San Francisco time, and two on London time, so there’s something everyone should be able to attend.

The ticket price is $100, but for that you can attend live, and watch or download session recordings later. You'll also receive a voucher to redeem against one free copy of any Hacking with Swift book, valid for six months. Yes, this applies to all books announced in the future – you won't miss out if you bought all my books already.

To see workshop dates, session lists, or to reserve your place, visit the Hacking with Swift Live homepage. I look forward to seeing you there!

I tried SE-0185 and it’s a thing of beauty https://www.hackingwithswift.com/articles/24/i-tried-se-0185-and-it-s-a-thing-of-beauty https://www.hackingwithswift.com/articles/24/i-tried-se-0185-and-it-s-a-thing-of-beauty A Google engineer is working to remove more drudgery from Swift. Fri, 29 Sep 2017 16:10:35 +0000 Even though Swift is for the most part a clean, modern language (let’s just pretend @objc doesn’t exist, OK?) it still has a few areas that are unnecessarily clunky.

For example, before Swift 4 came along it used to be mind-numbingly dull making your data types conform to NSCoding – it always meant writing near-identical boilerplate code to read and write all the properties you wanted to store.

Thanks to Swift 4’s Codable protocol that pain point has gone away, but work is underway to solve another annoyance: the need to write functions to make trivial data types conform to Equatable and Hashable.

To demonstrate the problem, consider this struct:

struct Person: {
    var firstName: String
    var lastName: String
    var age: Int
    var city: String
    var likesSinging: Bool

There’s nothing fancy there – a few strings, an integer, and a boolean. If we wanted to create a couple of instances of those structs, Swift provides us with a memberwise initializer so we can write code like this:

let taylor = Person(firstName: "Taylor", lastName: "Swift", age: 27, city: "Nashville", likesSinging: true)
let notTaylor = Person(firstName: "Taylor", lastName: "Swift", age: 27, city: "London", likesSinging: true)

The problem comes if we want to compare those two instances. They are almost the same, but not quite: one lives in London and the other in Nashville.

If we wanted to compare the two values to make sure they were different we would need to make Person conform to the Equatable protocol. In practice that means implementing the == function so that it returns true if two values match, which usually goes something like this:

struct Person: Equatable { 
    var firstName: String
    var ...
Interview: Janie Clayton https://www.hackingwithswift.com/articles/23/interview-janie-clayton https://www.hackingwithswift.com/articles/23/interview-janie-clayton We chat about community, Metal, Face ID, and more. Thu, 28 Sep 2017 21:59:00 +0000 In the first of a series of interviews with prominent members of the Apple development community, we spoke to Janie Clayton – a regular on the speaking circuit, author of an upcoming book on Metal, and a pug owner addict.

Swift Developer News: For readers who haven’t heard of you before, could you give a brief outline of your history as an iOS developer?

Janie Clayton: I originally got a degree in broadcast journalism and English composition. My hope at the time was to work in radio news at places like NPR or the BBC. I didn't get the memo that journalism, especially radio journalism, was basically dying and when I got out of school I couldn't find a job.

“I realized I had made some grievous errors and that I needed to make better decisions while I still had time to pivot to something else.”

Rather than being smart and doing something practical, I switched my focus to TV and went back to school to learn video production and audio engineering. About three weeks after I finished my degree the Great Recession hit. All of the places I thought I was going to work at went out of business or drastically reduced staff. I realized I had made some grievous errors and that I needed to make better decisions while I still had time to pivot to something else.

SDN: That’s a pretty grim time to graduate! So what did you do?

JC: I was either going to go to law school or become a programmer. I looked at how much law school cost compared to learning programming at the local community college and what the starting salaries for both were and it was kind of a no-brainer. I also noticed my fellow liberal arts refugees were flocking to law school looking for safe haven and I really didn't want to keep competing with them anymore.

I settled on iOS programming because it was relatively new at the time. People were desperate to hire anyone with any iOS experience and they were less picky about having you pass algorithm screens or have 5+ years of exp...

What's new in iOS 11.1 for developers https://www.hackingwithswift.com/articles/22/what-s-new-in-ios-11-1-for-developers https://www.hackingwithswift.com/articles/22/what-s-new-in-ios-11-1-for-developers After the behemoth of iOS 11, this is just a patch release. Wed, 27 Sep 2017 17:30:24 +0000 iOS 11 introduced a huge range of changes that are already revolutionizing app development, not least Core ML, ARKit, drag and drop, and more. Following that epic release, the first beta of iOS 11.1 was released today and so far mainly seems to be a few small tweaks to APIs that got missed off the initial iOS 11.0 release.

Note: iOS 11.1 is in early beta, and may continue to add features before reaching final release; this article will be updated as necessary.

There are two new APIs you should be aware of, one for activating the True Depth camera built into the new iPhone X, and one for detecting system pressure when capturing media. Both of these have been retrospectively marked @available(iOS 11.0, *), which means they shipped with iOS 11 but weren't made available until now.

First, the new True Depth camera. Here's how the Apple SDK describes it:

A device that consists of two cameras, one YUV and one Infrared. The infrared camera provides high quality depth information that is synchronized and perspective corrected to frames produced by the YUV camera. While the resolution of the depth data and YUV frames may differ, their field of view and aspect ratio always match.

You're probably already using the AVCaptureDevice.default() method for gaining access to media capture devices, and the True Depth camera fits right into that. Here's an example to get you started:

let trueDepthCamera = AVCaptureDevice.default(.builtInTrueDepthCamera, for: .video, position: .front)

As for the new system pressure system, this looks like it's designed to work around hardware limitations – if a device is unable to continue capturing media at the rate requested by a developer, the system pressure system is designed to interrupt the capture session until things calm down a little.

You can check the system pressure for your capture device by reading its new systemPressureState property. Here's how the iOS 11.1 SDK describes it:


How to localize your apps more easily https://www.hackingwithswift.com/articles/21/how-to-localize-your-apps-more-easily https://www.hackingwithswift.com/articles/21/how-to-localize-your-apps-more-easily Take your app around the world with smarter, simpler code Tue, 26 Sep 2017 07:55:46 +0000 Localization is one of those topics that never seems to get in-depth coverage: most developers largely ignore the topic, and others don’t even know how it works.

Regardless of how much you already localize your apps, Marco Santarossa has written a great set of tips to help you get started, including:

  • Extending String to make your code shorter.
  • Switching to enums for extra safety.
  • Using @IBInspectable to localize UIKit components in IB.
  • Pluralizing strings with numbers.

I’ve written similar code for localizing UIKit components, but his enum approach is brilliant in its simplicity. Of course, if Xcode actually had codegen for strings this wouldn’t be a problem, but until then I suggest you check out his article. Don't worry if you're completely new to localization – Marco gives you just enough at the beginning to help you get started, so there really is no excuse for not trying it.

Link: App Localization Tips With Swift

To notch or not to notch? NotchKit can help you decide. https://www.hackingwithswift.com/articles/20/to-notch-or-not-to-notch-notchkit-can-help-you-decide https://www.hackingwithswift.com/articles/20/to-notch-or-not-to-notch-notchkit-can-help-you-decide Try out both options and see what looks best Sun, 24 Sep 2017 16:27:54 +0000 Enterprising WWDC 2017 scholar Harshil Shah has created a framework that lets you simulate how your app could look on iPhone X if you wanted to try ignoring the notch.

His project, NotchKit, “is a simple way to hide the notch on the iPhone X and create a card-like interface for your apps,” and works by subclassing UIWindow so that you can choose to make apps that #EmbraceTheNotch or ignore it entirely if you prefer.

Shah makes it clear that Apple’s human interface guidelines ask developers not to try to hide the sensor housing, but much more interesting is his rationale for sharing his work:

It only took me a couple of days using the simulator to realise that embracing the notch is the way forward. My intention with open-sourcing this was to make it easier for others to reach that conclusion as well.

If you’re still on the fence about the notch – Notch or Not, as it were – perhaps you should give his framework a try and decide for yourself.

Link: NotchKit on GitHub

How weak references work in Swift 4 https://www.hackingwithswift.com/articles/19/how-weak-references-work-in-swift-4 https://www.hackingwithswift.com/articles/19/how-weak-references-work-in-swift-4 Curious about Swift's memory internals? Mike Ash has your back. Sat, 23 Sep 2017 19:11:13 +0000 Mike Ash's latest Friday Q&A takes a walk through weak references in Swift 4, comparing the old implementation against the new. From the article:

In the old implementation, Swift objects have two reference counts: a strong count and a weak count. When the strong count reaches zero while the weak count is still non-zero, the object is destroyed but its memory is not deallocated. This leaves a sort of zombie object sitting in memory, which the remaining weak references point to. When a weak reference is loaded, the runtime checks to see if the object is a zombie. If it is, it zeroes out the weak reference and decrements the weak reference count. Once the weak count reaches zero, the object's memory is deallocated. This means that zombie objects are eventually cleared out once all weak references to them are accessed.

In the old implementation, it's possible zombie objects could hang around long after they were needed, which could be a real waste of memory. Fortunately, times have moved on and Swift's new implementation manages to solve that problem using side tables. Mike explains:

Swift's new implementation of weak references brings with it the concept of side tables. A side table is a separate chunk of memory which stores extra information about an object. It's optional, meaning that an object may have a side table, or it may not. Objects which need the functionality of a side table can incur the extra cost, and objects which don't need it don't pay for it.

One thing I really enjoy about Mike's blog posts is that he is careful to link to the matching source code in Swift, so you can see for yourself exactly how things are implemented. Yes, I know all the Swift source code is there to read, but it can be so hard to find an entry point without someone to give you a pointer – make sure you read the whole article!

**Link: [Friday Q&A 2017-09-22: Swift 4 Weak References](https://www.mikeash.com/pyblog/friday-qa-...

How to make Xcode take up less space https://www.hackingwithswift.com/articles/18/how-to-make-xcode-take-up-less-space https://www.hackingwithswift.com/articles/18/how-to-make-xcode-take-up-less-space Xcode 9 is over 10GB, but that's only its starting size… Thu, 21 Sep 2017 19:51:47 +0000 We all know that Xcode has struggled with being a little on the portly side for some years, and even Apple acknowledged this back at WWDC 2012. Here’s what Matthew Firlik (Director of Development Technologies at Apple) had to say at the time:

Last year [at WWDC 2011] when we shipped Xcode 4.1 our download size was a little bit over 4 gigabytes, and I don't think there's anything more to be said about that. When we shipped Xcode 4.2 we were able to shrink that package size down to about 1.5 gigabytes by making some of the legacy content – like the older iOS simulators – downloadable on demand.

At the time that was a big and welcome improvement, but sadly it wasn’t to last: after going on its crash diet in 2012, Xcode has since been busy at the dessert aisle and has grown far beyond the “no more to be said about that” size of Xcode 4.1.

Let’s take a look at some figures:

Version Download Installed
Xcode 5.0 2.05 GB 4.37 GB
Xcode 6.0 2.62 GB 5.18 GB
Xcode 7.0 3.85 GB 7.79 GB
Xcode 8.0 4.41 GB 9.97 GB
Xcode 9.0 5.37 GB 10.41 GB

Now, some amount of natural fluctuation is to be expected – as Firlik said back in 2012, Apple can adjust its selection of simulators in order to reduce the initial download at the expense of possible later downloads.

It’s also important to note that Xcode has added features over those years, such as Swift in Xcode 6 or App Thinning in Xcode 7, so some amount of natural growth is inevitable. Many developers – myself included! – have a long wish list of features we want to see in Xcode 10, so there’s a never-ending trade-off between cutting size and adding features.

But wait – there’s more!

All this extra growth means that Xcode 9 is more than twice the size of Xcode 5, but even that’s not the whole story. You see, Xcode is a bit sneaky: the 10.41GB that Xcode 9 takes up is ac...

All Hacking with Swift books now updated for Swift 4 https://www.hackingwithswift.com/articles/17/all-hacking-with-swift-books-now-updated-for-swift-4 https://www.hackingwithswift.com/articles/17/all-hacking-with-swift-books-now-updated-for-swift-4 Book updates are free thanks to my lifetime update policy Wed, 20 Sep 2017 08:50:33 +0000 With yesterday's release of Xcode 9, all 11 books in the Hacking with Swift series have been updated for Swift 4. These updates are available free of charge thanks to the Hacking with Swift lifetime update policy, which guarantees you Swift updates for the life of each book.

If you bought through Gumroad: The book updates are available immediately using your original email receipt. Look for the product download link from Gumroad, and that should take you straight to the updated editions.

If you bought through iBooks: The updates have been submitted to Apple for review and will hopefully be live in the next few days.

If you're keen to learn more, here are links to each of the books:

At the same time as updating the books for Swift 4 some other enhancements were added, including:

  • Hacking with Swift now explains how to adopt the large title bars introduced in iOS 11, how to use the safe area and hide the home indicator for iPhone X, and how to use the new Swift 4 Codable protocol to load and save data.
  • Pro Swift has been expanded to cover fatalError(), Never, and Swift 4 dictionary improvements.
  • Hacking with watchOS now teaches how to enable auto rotation and Water Lock in your apps.

As well as the books being refreshed, the Swift Test has been updated for Swift 4, and the Swift Knowledge Base has been updated for Swift 4 and expanded with new articles relating to iOS 11 and iPhone X. Th...

Xcode 10 wish list: native iOS support, codegen, and more https://www.hackingwithswift.com/articles/16/xcode-10-wish-list-native-ios-support-codegen-and-more https://www.hackingwithswift.com/articles/16/xcode-10-wish-list-native-ios-support-codegen-and-more Now that Xcode 9 is out it’s time to look forward to next year Tue, 19 Sep 2017 19:43:46 +0000 Xcode 9 was released on the Mac App Store a few hours ago, and there’s no doubt it’s the most feature-packed Xcode release to date. Not only does it include faster editing, named colors, Swift refactoring, and wireless debugging, but it also comes with a huge simulator revamp that allows us to run multiple simulators at the same time.

So, now we’re free to look forward to Xcode 10 and start thinking: what features would we most want to see added in Xcode 10? Or is it Xcode X? Here are some to get you started…

Codegen for assets

Codegen – the practice of generating code either statically or dynamically – has been in Xcode for some time, for example when generating Core Data classes. In Xcode 9 this was taken further so that Core ML models also have their classes generated dynamically at build time so that developers never have to worry about their internals.

However, large parts of both macOS and iOS rely on strings to work: table view cell identifiers, storyboard identifiers, image names, and more are all as stringly typed as they come. In Swift 4, many macOS APIs have veered away from strings in favor of strongly typed typedefs like this:

typedef NSString *NSImageName;

If Objective-C isn’t your bag, that translates more or less as “whenever we say NSImageName we really mean NSString”. That has no impact to Objective-C developers because they can continue providing strings for image names as they always did, but Swift developers must now use NSImage.Name for all their image names, like this:

let img = NSImage(named: NSImage.Name("banner"))

The goal here is to encourage developers to create static variables for each of their names so they can instead write:

let img = NSImage(named: Assets.banner)

This has the advantage of eliminating typos and duplication when using the same image in many places, although it does mean you need to put in the extra work to define all your images up fron...