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 Sherlock turbocharges your iOS simulator https://www.hackingwithswift.com/articles/131/sherlock-turbocharges-your-ios-simulator https://www.hackingwithswift.com/articles/131/sherlock-turbocharges-your-ios-simulator Inspect and adjust any app in real time Thu, 08 Nov 2018 10:55:31 +0000 There aren’t many times outside of WWDC where Apple developers see a new tool and immediately think “I need that in my life.” Sherlock by Inspired Code is one such tool: it injects itself into the iOS Simulator so that it can monitor views and adjust them in real time.

If you aren’t already thinking you need that, let me rephrase what I just said: you can inspect any app in the simulator, including system apps, see how they were built, and dynamically change large parts of them. Want to adjust the way image views fit their images, how text is aligned, or what background color is used? Sherlock does all those things and more – you just select the thing you want to change and click away until you’re happy.

When working with one of your own apps, Sherlock provides an unparalleled ability to experiment: navigate your way through your view hierarchy, select something you want to work with, then adjust any number of settings right from a macOS window. And when you want to compare your changes to the code, there’s even a “Jump to File” button that takes you straight there.

Even more impressively, you can attach a resizable screen to any app, allowing you instantly flick between various common iOS device sizes: iPhone 5, 6, and X are all available. Selecting a size immediately updates the layout to how it would look on the new device – it’s not just stretched to fit.

Right now the app is available as a free beta, so there really is no reason not to give it a try. In the future it would ...

]]>
Vote in the Swift Community Awards 2018 https://www.hackingwithswift.com/articles/130/vote-in-the-swift-community-awards-2018 https://www.hackingwithswift.com/articles/130/vote-in-the-swift-community-awards-2018 Help recognize and celebrate the people and projects that make our community amazing! Sat, 13 Oct 2018 09:50:30 +0000 The first stage of the Swift Community Awards for 2018 is now open, meaning that everyone can nominate the people and projects that have helped them the most over the year.

There are twelve categories in total, and you can add your nomination in as many or as few as you wish. The categories are: Best Newsletter, Best Conference, Best Podcast, Best Design Resource, Best Deployment Tool, Best Backend Service, Best Developer Tool, Best Enterprise SDK, Best Server-Side Swift Project, Best Auto Layout Wrapper, Best Open-Source Project, and Most Inspiring Presentation.

The nominations phase runs through to October 30th, at which point votes will be counted up and used to make a shortlist that everyone can vote for.

So, if there’s a particular project that has helped you, a presentation that’s inspired you, or a podcast that’s made you laugh or learn, this is your chance to show your gratitude by nominating them for an award.

]]>
Conference report: NSSpain 2018 https://www.hackingwithswift.com/articles/129/conference-report-nsspain-2018 https://www.hackingwithswift.com/articles/129/conference-report-nsspain-2018 Swift, wine, and good times come back to Logroño Sun, 07 Oct 2018 13:39:56 +0000 "You’re going to NSSpain? That’s the best conference." That’s what I was told just 24 hours before flying out to the heart of La Rioja province for the world-renowned iOS conference.

Everyone knows NSSpain is famous, but it’s hard to be sure why. It might be their ability to get incredible speakers time and time again, it might be the huge and beautiful venue, or it might be the fact that the event ends just as the San Mateo wine festival starts in the same town – lots of folks stay an extra day or two just for that event.

This year’s line up included Kristina Fox, Daniel Steinberg, Dave DeLong, Adam Bell, Ellen Shapiro, and Benedikt Terhechte, delivering a wide range of talks about Siri shortcuts, combinators, app architecture, and more. My own talk was about building and running Hacking with Swift, covering the most common problems folks hit when learning Swift and what it tells us about our platform – you can watch it here.

I think it’s safe to say, though, that the star of the stage was Guilherme Rambo, delivering his first presentation in Europe. His talk, The Art of Spelunking, gave a whirlwind tour through his approach to finding hidden curiosities in iOS, including how he learned so much about the HomePod ahead of its release.

One of the many things that NSSpain does right is encouraging new speakers, even disallowing speakers from presenting two years in a row. This year saw several new speakers delivering great presentations – I particularly enjoyed Daniel Munoz’s talk on internationalization, and Nelida Velazquez’s talk on working with legacy projects.

At the end of the first conference day two special events took place. First, John Sundell and Gui Rambo took to the stage to deliver a live edition of their Stacktrace podcast. As Apple’s September event had only just happened there was a lot to discuss, but as lively as that was the following event was even busier thanks to it being a wine-tasting to...

]]>
Array performance: append() vs reserveCapacity() https://www.hackingwithswift.com/articles/128/array-performance-append-vs-reservecapacity https://www.hackingwithswift.com/articles/128/array-performance-append-vs-reservecapacity Sometimes its faster to let Swift figure things out for you Thu, 04 Oct 2018 13:14:32 +0000 If you’re adding lots of items to an array, you might find it more efficient to tell Swift ahead of time how much capacity you need by using the reserveCapacity() method on your collection. However, while this method can indeed make your code faster, if you’re not careful it can also make it a lot, lot slower, so be careful.

First, let’s take a look at how array storage works. If you create an array with four items, Swift will allocate enough capacity for that array to hold only those four items. So, both yourArray.count and yourArray.capacity will be equal to 4.

Now let’s say you want to append a fifth item. The array doesn’t have capacity for that, so it needs to make some space – it will find memory to hold more items, copy the array there, then append the fifth item. This has an O(n) run time, where n is the number of items in the array.

To avoid constant reallocations, Swift uses a geometric growth pattern for array capacities – a fancy way of saying that it increases array capacity exponentially rather than in fixed amounts. So, when you add a fifth item to an array with capacity 4, Swift will create the resized array so that it has a capacity of 8. And when you exceed that you’ll get a capacity of 16, then 32, then 64, and so on – it doubles each time.

Now, if you know ahead of time that you’ll be storing 512 items, you can inform Swift by using the reserveCapacity() method. This allows Swift to immediately allocate an array capable of holding 512 items, as opposed to creating a small array then re-allocating multiple times.

For example:

var randomNumbers = [Int]()
randomNumbers.reserveCapacity(512)

for _ in 1...512 {
    randomNumbers.append(Int.random(in: 1...10))
}

reserveCapacity() also has an O(n) run time based on the number of elements in the array, so you should definitely call it when the array is still empty.

But there’s a catch, and it’s an important one: you need to be sure that your array gr...

]]>
Conference report: Swift & Fika https://www.hackingwithswift.com/articles/127/conference-report-swift-fika https://www.hackingwithswift.com/articles/127/conference-report-swift-fika Sweden’s new Swift conference aces its first year. Tue, 25 Sep 2018 13:56:24 +0000 Swift & Fika is an all-new Swift conference in Stockholm, but honestly you’d never know unless you were told – the organization was slick, well-known speakers flew in from around the world, and the organizing team were relaxed and enjoying the event as much as everyone else.

As is increasingly common in community-driven events, Swift & Fika started with a day-long selection of social events: a bike tour of the city, bouldering, museum tours, and even a VR experience all helped to encourage attendees to make friends, and to top it off there was a “dinner with strangers” event in the evening. In my experience this can be so beneficial, even if you’re not naturally that social – when the conference starts it means you recognize more friendly faces, and you hopefully have more opportunities to discuss talks with people you met.

The conference day was split up into talks from nine speakers, including Janina Kutyn on app performance, JP Simard on Swift static analysis, John Sundell on API design, and Anastasiia Vixentael on app security. This was the first time I’ve seen Yoichi Tagaya speak about his work - he’s the creator of the popular Swinject dependency injection tool, and it was a real privilege to have him join us all the way from Tokyo. My own talk was called “How Not to Write Swift”, for which I bought a special prop: The Hoodie of Truth.

To help keep the whole event fairly relaxed, Swift & Fika had two secret weapons. First, the MC was Jack Nutting, who introduced all the speakers and provided some comic relief with live musical numbers. And second was the fika – officially it’s Swedish for “break time”, but in practice it means chatting over coffee and cinnamon buns or other delights. As useful as the main presentations were, the fika time meant that everyone could mingle, make friends, and hopefully build relationships that will last long after the event has finished.

Finishing off the day was a remarkable after-party at Spotify’s headquarters. As well as h...

]]>
What’s new in Swift 5.0 https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0 https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0 Raw strings, future enum cases, compactMapValues(), and more! Mon, 17 Sep 2018 15:49:52 +0000 Swift 5.0 is the next major release of Swift, and is slated to bring ABI stability at long last. That's not all, though: several key new features are already implemented, including raw strings, future enum cases, checking for integer multiples and more.

If you want to try out Swift 5.0 ahead of its release early next year, download the latest Swift trunk development snapshot, activate it inside your current Xcode version, then follow along with my examples below!

Raw strings

SE-0200 added the ability to create raw strings, where backslashes and quote marks are interpreted as those literal symbols rather than escapes characters or string terminators. This makes a number of use cases more easy, but regular expressions in particular will benefit.

To use raw strings, place one or more # symbols before your strings, like this:

let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#

The # symbols at the start and end of the string become part of the string delimiter, so Swift understands that the standalone quote marks around “rain” and “Spain” should be treated as literal quote marks rather than ending the string.

Raw strings allow you to use backslashes too:

let keypaths = #"Swift keypaths such as \Person.name hold uninvoked references to properties."#

That treats the backslash as being a literal character in the string, rather than an escape character. This in turn means that string interpolation works differently:

let answer = 42
let dontpanic = #"The answer to life, the universe, and everything is \#(answer)."#

Notice how I’ve used \#(answer) to use string interpolation – a regular \(answer) will be interpreted as characters in the string,...

]]>
Conference report: iOSDevUK 8 https://www.hackingwithswift.com/articles/125/conference-report-iosdevuk-8 https://www.hackingwithswift.com/articles/125/conference-report-iosdevuk-8 The UK's oldest conference is now in its eighth year Sun, 16 Sep 2018 21:40:24 +0000 iOSDevUK has a special place in the hearts of many British developers, partly because it's been going so long, partly because it has a unique setting, and partly because it's a multi-day event where you really get to know folks.

If you haven't attended before, the conference takes place in the Welsh university town of Aberystwyth, which is fairly remote. A running joke is that the train to the town is four to five hours for everyone, and is a bit like the Hogwarts Express because it's full of folks going to the event.

This relative isolation is what gives iOSDevUK its unique atmosphere: you're there from Monday to Thursday, all staying together in student accommodation, and eating three meals a day together either in the university restaurants or at various social events, so you have many chances to make new friends. There's even a group steam train ride through the Welsh countryside – make sure you bring your camera!

I was lucky enough to give both a workshop on Monday and the closing presentation on Thursday, but of course I was able to attend some great sessions too. Particular favorites were Steve Scott's talk "The Mark of Great Developer", Tim Condon's talk "Why server-side Swift?", Daniel Leivers’s talk "An introduction to GraphQL", and Joachim Kurz's talk "There's a formatter for that" – an eye-opening session showing us all just how little we know about localization in practice.

It was also great to see Dave Verwer of iOS Dev Weekly fame delivering a talk about product management for indie developers. Top tip: if you want folks to answer a questionnaire offer them Amazon gift cards rather than cash, because cash can be used on boring things like tax and mortgages whereas Amazon gift cards always mean something more fun.

iOSDevUK combines a truly enjoyable learning environment with startlingly low ticket prices – as low as £150 for three full days of conferencing – so it’s no surprise folks keep coming back. I’m already looking forward to the ninth edition next year!

]]>
Swift Knowledge Base updates for Swift 4.2 https://www.hackingwithswift.com/articles/124/swift-knowledge-base-updates-for-swift-4-2 https://www.hackingwithswift.com/articles/124/swift-knowledge-base-updates-for-swift-4-2 Now containing 600 tips and examples for Swift! Sun, 02 Sep 2018 09:12:39 +0000 Now that I'm back from my summer vacation, I've updated the Swift Knowledge Base with key examples from Swift 4.2 to make everything easier to find. More updates will come shortly after Swift 4.2 ships as final, but the list below is a good starting point:

New articles:

Updated articles:

With those new articles, the Swift Knowledge Base now contains 600 tips and examples for Swift developers, all constantly being updated as Swift evolves.

]]>
Learn Core Graphics with Swift Playgrounds https://www.hackingwithswift.com/articles/123/learn-core-graphics-with-swift-playgrounds https://www.hackingwithswift.com/articles/123/learn-core-graphics-with-swift-playgrounds Take on a fundamental Apple API right on your iPad Sat, 16 Jun 2018 16:31:44 +0000 I just released my first ever playground book for Apple's Swift Playgrounds app on iPad: Learn Core Graphics. This gives you the ability to work through examples of drawing shapes, text, images, and more, all while seeing the results of your code played back right next to it.

The free book is structured as a series of challenges of increasing difficulties, and by the end you'll have learned a fair chunk of Core Graphics that you can then go on to apply elsewhere. Because it uses the real Core Graphics API rather than a simplified approach, you can literally take the code you wrote and apply it directly in your own iOS apps.

If this first book benefits enough people it's likely I'll do more in the future. So, give it a try and let me know what you think!

To learn more, and subscribe to the playground, go to this page on an iPad that has Swift Playgrounds installed: Hacking with Swift in Swift Playgrounds. You'll see a "Click to Subscribe" button there that only works on iPads with Swift Playgrounds installed, and it will subscribe you to my playgrounds feed.

]]>
Conference report: WWDC18 https://www.hackingwithswift.com/articles/122/conference-report-wwdc18 https://www.hackingwithswift.com/articles/122/conference-report-wwdc18 Our community’s biggest conference is over for another year Thu, 14 Jun 2018 06:10:32 +0000 Every year WWDC seems to grow bigger, and although 2018 didn’t provide the same astonishing new features we saw last year the event itself continues to be the greatest meetup of Apple developers in the world. You meet people you normally only see on Twitter, you get to ask questions to Apple developers who work on the frameworks you’re using, and you can meet a huge range of people at the many and varied social events in the evenings.

Let’s break it down…

Announcements

By now you’ll have seen that the focus of WWDC this year is performance and stability, giving all of us a welcome break from the upgrade treadmill. That doesn’t mean it’s all quiet, though: new features in iOS 12 and macOS Mojave include Create ML, alert grouping, Siri Shortcuts, the Natural Language framework, and more.

Of all the new announcements, Siri Shortcuts is the one that has the power to change apps most dramatically. If you haven’t tried it out yet, Shortcuts allow you to direct the user to specific parts of your app based on custom voice commands. It’s not quite full Siri integration, but it’s a huge step forward and I’m looking forward to seeing what apps can do with it.

This year also saw the deprecation of UIWebView, which has served us well for over a decade. I know that WKWebView and SFSafariViewController provide full replacements these days, but I think we can all agree that UIWebView has served us well and deserves an honorable discharge from UIKit.

Sessions

With slim pickings on the new feature front, it won’t be a surprise to hear that some of the major sessions – ARKit, and Core ML – were packed to overflowing, so you either started getting in line early or you didn’t get in.

On the flip side, a lack of new features meant Apple had to up its game a little: there was little scope for “introduction to…” talks because they had all been covered in previous years, so as a result there were many more advanced talks:...

]]>
What’s new in iOS 12? https://www.hackingwithswift.com/articles/121/whats-new-in-ios-12 https://www.hackingwithswift.com/articles/121/whats-new-in-ios-12 Learn what developer features have changed and how to use them Tue, 05 Jun 2018 06:58:07 +0000 iOS 12 brings with it huge leaps forward in machine learning, new ways to work with text, alert grouping so that users are bothered less frequently, and more. Part of this comes through huge improvements to Xcode, but I'll be covering it all here.

In this article I'm going to walk you through the major changes, complete with code examples, so you can try it all for yourself. Right now you can try iOS 12 only using the beta version of Xcode, and you will also need macOS Mojave if you want to use the new Create ML tools.

 

NEW: You can now pre-order my new book, Practical iOS 12! It's available at 50% off for the next few days, so be quick – click here to find out more!

Watch the video

If you prefer seeing these things like, I recorded a YouTube video showing of all the below and more.

Prefer reading instead? Then here we go…

Machine learning for image recognition

Machine learning (ML) was one of several major announcements from iOS 11, but it wasn't that easy to use – particularly for folks who hadn't studied the topic previously.

This is all changing now, because Apple introduced two important new pieces of functionality. The first – Create ML – is actually a macOS framework that's designed to make it trivial for anyone to create Core ML models to use in their app. The second – prediction batching – allows Core ML to evaluate many input sources in a more efficient way, making it less likely that newcomers would make basic mistakes.

Create ML has to seen to be ...

]]>
iOS 12.0 API Diffs https://www.hackingwithswift.com/articles/120/ios-12-api-diffs https://www.hackingwithswift.com/articles/120/ios-12-api-diffs Everything that has changed in one place Mon, 04 Jun 2018 21:59:12 +0000 div.api-diffs { margin-top: 30px; } div.api-diffs .a::before { content: "Added"; color: blue; font-size: 70%; font-style: italic; padding-left: 20px; } div.api-diffs .r::before { content: "Removed"; color: red; font-size: 70%; font-style: italic; padding-left: 20px; } div.api-diffs .m::before { content: "Modified"; color: green; font-size: 70%; font-style: italic; padding-left: 20px; } div.api-diffs code { color: black; background-color: inherit; font-size: 80%; font-family: monospace; } p.api-diffs-settings { text-align: center; } p.api-diffs-settings .btn-primary { background-color: #337ab7; border-color: #2e6da4; } .api-diff-hidden { display: none; } span.api-diff-summary { font-size: 80%; } h4 { color: #666666; } div.api-diff-file { margin-top: 40px; } div.api-diff-file:first-child { margin-top: 0; } div.api-diffs table { border: 1px solid #999999; margin-top: 5px; margin-bottom: 20px; margin-left: 40px; max-width: 90%; } div.api-diffs td { padding: 5px; border: 1px solid #999999; } div.api-diffs th { text-align: center; padding: 5px; background-color: #f0f0f0; border: 1px solid #999999; border-top: #999999; font-size: 70%; } div.api-diffs .table > tbody > tr > th { border-top: #999999; }