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 What’s the difference between map(), flatMap() and compactMap()? https://www.hackingwithswift.com/articles/205/whats-the-difference-between-map-flatmap-and-compactmap https://www.hackingwithswift.com/articles/205/whats-the-difference-between-map-flatmap-and-compactmap Three common functional methods explained. Mon, 14 Oct 2019 19:59:28 +0000 Swift gives us map(), compactMap() and flatMap() methods, but although they might sound similar they do very different things. So, in this article we’ll look at map() vs compactMap() vs flatMap() to help you understand what each one does and when it’s useful.

The word all three methods share is “map”, which in this context means “transform from one thing to another.” So, the map() method lets us write code to double all the numbers in an array:

let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }

That will take each value in the array and run it through our closure, where $0 refers to the number in question. So, it will be 1 2, 2 2, 3 * 2, and so on – map() will take a value out of its container, transform it using the code you specify, then put it back in its container. In this case, that means taking a number out of an array, doubling it, and putting it back in a new array.

It works on any data type, so we could use it to uppercase an array of strings:

let wizards = ["Harry", "Hermione", "Ron"]
let uppercased = wizards.map { $0.uppercased() }

map() is able to return a different type from the one that was originally used. So, this will convert our integer array to a string array:

let numbers = [1, 2, 3, 4, 5]
let strings = numbers.map { String($0) }

Things get a little trickier if we go in the opposite direction – if we try to convert those strings back into integers. This is because strings can contain any value: “1”, “5”, and “500” are all strings that can safely be converted to integers, but “Fish” is not. As a result, converting a string to an integer returns an optional integer.

To see this in action, this code uses map() to convert a string array into an array of optional integers:

let maybeNumbers = strings.map { Int($0) }

compactMap(): transform then unwrap

Working with optionals can be annoying, but compactMap() can make life much easier: it performs a tran...

]]>
How to use Core Image filters the type-safe way https://www.hackingwithswift.com/articles/204/how-to-use-core-image-filters-the-type-safe-way https://www.hackingwithswift.com/articles/204/how-to-use-core-image-filters-the-type-safe-way iOS 13 fixed this once and for all Wed, 09 Oct 2019 09:52:25 +0000 iOS 13 introduced new type-safe initializers for Core Image filters that allow us to use them much more easily – and without having to hope that our code works at runtime. Previously much of Core Image was stringly typed, meaning that we would create filters using strings, which in turn meant that Swift couldn't be sure that when we asked for a value to be set that it would actually exist. iOS 13 replaces that with a much better implementation, and you'll never want to go back to the old way.

This functionality is enabled by new protocols that define exactly what each filter can do. For example, CILinearGradient has two points and two colors, while CIBarsSwipeTransition has an angle, a width, and a bar offset. So, while we aren't getting concrete types back, the protocols at least mean we have guaranteed access to all the properties we need.

Start by adding an import to bring in all the new types:

import CoreImage
import CoreImage.CIFilterBuiltins

Now you can go ahead and create filters using static methods on CIFilter. For example, CIFilter.qrCodeGenerator() sends back a filter to generate QR codes. Once you have the type you want, you'll find properties you can set specific to that filter, which is a huge improvement over the old calls to setValue(_forKey:).

For example, we could we create a Gaussian blur effect using CIFilter.gaussianBlur(), set its input image and radius, then read out the result:

let context = CIContext(options: nil)
let blur = CIFilter.gaussianBlur()
blur.inputImage = CIImage(image: exampleImage)
blur.radius = 30

if let output = blur.outputImage {
    if let cgimg = context.createCGImage(output, from: output.extent) {
        let processedImage = UIImage(cgImage: cgimg)
        // use your blurred image here
    }
}
]]>
How to use SwiftUI in Swift Playgrounds https://www.hackingwithswift.com/articles/203/how-to-use-swiftui-in-swift-playgrounds https://www.hackingwithswift.com/articles/203/how-to-use-swiftui-in-swift-playgrounds Get started with SwiftUI right on your iPad Wed, 02 Oct 2019 11:48:42 +0000 Apple just updated its Swift Playgrounds iPad app with support for Swift 5.1, dark mode, and SwiftUI, which means it’s now possible to try building SwiftUI apps and components entirely on your iPad.

Although Swift Playgrounds comes with a handful of templates for various kinds of projects, none of them are for SwiftUI – at least not yet. Hopefully that will change in the near future, not least because we’re approaching Code Week here in the EU – it would be great to see Apple taking Everyone Can Code to the next level with something based around SwiftUI.

In the meantime, if you want to get started you can create a new Blank Playground then add your code there. It takes a little boilerplate, so to save you some time here’s the code you need to get started:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

PlaygroundPage.current.setLiveView(ContentView())

At this time support for SwiftUI isn’t ideal: NavigationView doesn’t work well because it tries to run as a split view controller, and there is no support for the instant preview canvas that we get with Xcode – you need to keep tapping “Run My Code”.

Still, it’s a massive leap forward, and is only going to improve. And don’t forget that even without SwiftUI you still get all the benefits of iOS 13, including the new Swift 5.1 opaque return types, Combine, and more.

If you’d like to learn more about how to use SwiftUI to build apps, you should read my free online book: SwiftUI by Example. You might also want to try my 100 Days of SwiftUI course, which teaches you SwiftUI as you build real apps.

]]>
Swiftoberfest 2019 https://www.hackingwithswift.com/articles/202/swiftoberfest-2019 https://www.hackingwithswift.com/articles/202/swiftoberfest-2019 Get schwifty with Swift and SwiftUI Mon, 30 Sep 2019 20:27:45 +0000 Swiftoberfest is over for this year! 62 new articles from me (and over a dozen reader submissions) should give you lots of reading as the nights grow longer. Next stop: Swiftmas!


Here in the UK the nights are starting to grow longer as we edge towards winter, so I figured it would be a good time to invent a new holiday shakily stolen from Bavaria’s annual Oktoberfest celebration. So, I’m pleased to introduce you to Swiftoberfest: an all-new way to help you learn throughout October.

Here’s how it works: every day in October, from the 1st to the 31st, I’ll be posting a new article here on Hacking with Swift. This will mostly be additions to my Swift Knowledge Base, but there will be some longer ones too.

Yes, this is in addition to me posting a new article every day for my 100 Days of SwiftUI.

So, if you’re following the 100 Days course and Swiftoberfest you’ll get two new articles every day.

Now, I have some bad news and some good news.

First, the bad news: none of those new articles will be about SwiftUI. Yeah, I know – SwiftUI is the cool new kid on the block, but also need to pay some attention to the wealth of other marvelous things Apple make available to us.

Now for the good news: if you follow me on Twitter you’ll know I spend far too much time noodling around with SwiftUI to leave it alone for a whole month.

So I thought to myself: what if I could write a 100 Days of SwiftUI article, a new knowledge base article, and an addition to SwiftUI by Example – three articles every day for a month? Could I do that while also speaking at Mobiconf in Poland and Pragma Conference in Italy?

More importantly, should I do that?

Of course you know the answer already, which is why you know I’m going for the big three: **every day for October you’ll get a new chapter in SwiftUI By Example, a new entry in my Swift Knowledge Base or longer article, plus a...

]]>
Start the 100 Days of SwiftUI! https://www.hackingwithswift.com/articles/201/start-the-100-days-of-swiftui https://www.hackingwithswift.com/articles/201/start-the-100-days-of-swiftui My new, free course starts today – join in! Mon, 23 Sep 2019 13:29:33 +0000 If you're looking for free SwiftUI tutorials, I have just the thing for you: the 100 Days of SwiftUI is an all-new online course teaching you how to build a variety of real-world apps with SwiftUI. The course starts with the same 15-day Swift fundamentals from the original 100 Days of Swift, but the next 85 days are all-new, project-based tutorials teaching SwiftUI.

Now obviously putting Swift and UI in the same name tells you exactly what SwiftUI is for, but this tutorial series won't just focus on UI design – we'll also be looking at how SwiftUI's property wrappers work, what view builders really are under the hood, accessibility, performance, Core Data, and more. We'll even be covering some machine learning with Core ML and Create ML, all for free.

Some folks have asked whether the 100 Days of SwiftUI will be reusing material from my existing SwiftUI book, SwiftUI by Example. The answer is a definitive no: this will be all new tutorials, challenges, and quizzes designed to help you learn SwiftUI in an enjoyable, hands-on way.

Today is the first day of the 100, and if you start today you finish on December 31st – just in time to start 2020 off with an incredible new skillset.

So, if you want to take onboard the exciting new challenge of SwiftUI, the 100 Days of SwiftUI is the perfect opportunity – get started today!

]]>
Xcode 12 wish list: SwiftUI, iPadOS, and more https://www.hackingwithswift.com/articles/200/xcode-12-wish-list-swiftui-ipados-and-more https://www.hackingwithswift.com/articles/200/xcode-12-wish-list-swiftui-ipados-and-more With nine months before WWDC20 now is the time to dream. Fri, 20 Sep 2019 17:04:04 +0000 Xcode 11 is about to ship as gold master, which means Apple’s teams are already hard at work on future features. Although it’s always nice to have surprise new functionality, it’s also smart to let Apple know what features would make the biggest difference to us, and now – with nine months until WWDC20 – is the perfect time.

So, I put together my wishlist for Xcode 12, and also asked the community what they most wanted to see. Unsurprisingly I was inundated with responses – as much as we love working with Xcode, there are always things it can do better.

Let’s dive in…

SwiftUI or bust

WWDC19 came with lots of massive announcements from Apple, but almost all of them were swept away by the behemoth that is SwiftUI. Although it’s still very early in SwiftUI’s public life, it seems pretty clear this is going to be the future of Apple development – we’re only really seeing the tip of what this technology can do.

So, what could Xcode 12 bring for SwiftUI? Here’s Luis Ascorbe, who helps organize NSSpain:

This view is surprisingly common: iOS 13.0 hasn’t been a particularly great release for developers, and is shipping with quite a few bugs. The fact that iOS 13.1 is already only days away – presumably as close as Apple’s dares to come to a day one patch without incurring a PR nightmare – says a lot about the stability of the initial release, and iOS 13.1 definitely fixes a raft of SwiftUI bugs.

What we don’t know yet is whether Apple will version gate existing SwiftUI functionality. That is, if an app looks a certain way because of a bug in iOS 13.0’s SwiftUI, will that app automati...

]]>
Avoiding near-duplicates in sets https://www.hackingwithswift.com/articles/199/avoiding-near-duplicates-in-sets https://www.hackingwithswift.com/articles/199/avoiding-near-duplicates-in-sets Decide for yourself what makes two objects equal Thu, 19 Sep 2019 11:33:28 +0000 Julian Schiavo writes, “I'm using a Set to make sure my array only contains uniques, but each object in the set has a date variable. This is causing duplicates when the data is refreshed and gets a different generation date. What would be the recommended solution for this?”

This is a great question, and Swift’s protocols help us make a really smart solution.

First, let’s take a look at some example code. Here’s an example NewsStory struct that tracks an ID, a title, plus a date:

struct NewsStory {
    var id: Int
    var title: String
    var date = Date()
}

As you can see, I’ve made the date automatically assigned so that it’s always the current date.

Using that struct we can create three news stories like this:

let story1 = NewsStory(id: 1, title: "What's new in Swift 5.1?")
let story2 = NewsStory(id: 2, title: "What's new in Swift 6.0?")
let story3 = NewsStory(id: 3, title: "What's new in Swift 6.1?")

Julian wants to store those news stories in a set instead of an array, which is a sensible choice. So, we want to write code like this:

var stories = Set<NewsStory>()
stories.insert(story1)
stories.insert(story2)
stories.insert(story3)
print(stories)

That creates a set of news stories, adds our three, then prints out the set. However, that code won’t compile: in order for Set to be able to identify each item uniquely we need to make NewsStory conform to Hashable so that it can generate a unique hash value representing the contents of each news story.

Swift is really smart here, because if add a Hashable conformance to a custom type that only has hashable properties it can do the rest of the work for us to calculate the hash value of our type. So, we need to update the NewsStory struct to this:

struct NewsStory: Hashable {
    var id: Int
    var title: String
    var date = Date...
]]>
Hacking with Swift site refresh https://www.hackingwithswift.com/articles/198/hacking-with-swift-site-refresh https://www.hackingwithswift.com/articles/198/hacking-with-swift-site-refresh Smarter! Faster! Darker! Mon, 16 Sep 2019 14:44:48 +0000 Two months ago Hacking with Swift passed 25 million page views, which is a huge accomplishment that I’m really proud of. I wanted to celebrate with something special, so I decided it was time to implement our #1 most requested feature: site search.

Site search was something I listed in my plans for 2019 nine months ago, and it’s been something folks have been requesting as long as I can remember. Of course, when I sat down to actually make site search happen I ended up changing practically everything else at the same time, and the result was the third major site update for Hacking with Swift.

Let me talk you through what’s changed…

Site search at last

Yes, I set out to make site search work, and obviously it would suck if that got missed out during the big refresh!

So, now you’ll see a permanent search box in the top-right corner of every page (or hidden behind the burger menu if you’re on mobile), along with a large search box on every page. This uses a full-text search of all articles, example code, tutorials, guide, and more, so you can be sure you’re seeing across the whole site.

But I wanted to take search one step further: you can now go straight to hackingwithswift.com/your-search-term to search across the site immediately. Here are some examples to get you started:

And yes, you can include spaces if you want – just enter “hackingwithswift.com/“ followed by anything you want to search for.

Dark mode

Site search was always the most-requested feature, but not far after was support for a dark theme. Well, it’s now active, and it’s automatic depending on the setting of your device – if you use dark mode on macOS or iOS, you’ll get dark mode here.

To help ensure readability I’ve bumped up the weights of almost al...

]]>
Hacking with Swift Live 2019 raises $30,000 for charity https://www.hackingwithswift.com/articles/197/hacking-with-swift-live-2019-raises-30-000-for-charity https://www.hackingwithswift.com/articles/197/hacking-with-swift-live-2019-raises-30-000-for-charity Thank you to all our speakers, attendees, and volunteers! Thu, 18 Jul 2019 23:05:12 +0000 The first Hacking with Swift Live took place last week in Bath, England, with all profits being donated to Special Effect – a charity that aims to put fun and inclusion back into the lives of people with physical disabilities by helping them to play video games.

We had eight fantastic speakers on day one: John Sundell kicked us off with an introductory keynote on generics, followed by Kilo Loco, Kelly Hutchison, and Daniel Steinberg rounding up before lunch with a talk about the Swift behind SwiftUI. In the afternoon Ellen Shapiro talked about Swift Package Manager, followed by Sally Shepard and Cory Benfield, before James Thomson closed the day with his incredible talk An Illustrated History of Easter Eggs.

All these talks are now available to watch on YouTube:

Day two was dedicated to hands-on tutorials of the major new features introduced from WWDC19, including SwiftUI, compositional layouts for collection views, diffable data sources, storyboard dependency injection, and more – we worked through three example projects demonstrating so many new things.

Even though this was our first event, we sold all our tickets, and also had support from incredible sponsors: Bitrise and Cookpad were generous enough to come on as platinum sponsors, and Compare the Market, Dyson, Ecot...

]]>
Learn SwiftUI with free tutorials https://www.hackingwithswift.com/articles/196/learn-swiftui-with-free-tutorials https://www.hackingwithswift.com/articles/196/learn-swiftui-with-free-tutorials Want to learn SwiftUI? Start here. Fri, 14 Jun 2019 12:33:37 +0000 SwiftUI was announced during the keynote at WWDC19, and already there are a huge number of free tutorials as articles, YouTube videos, books, and more – it’s safe to say that folks are really excited, and are keen to share that excitement with the world.

I’ve been creating a huge range of SwiftUI tutorials myself, but I’ve also been reading tutorials from many other developers. In this article I’ve tried to bring together tutorials from a variety of folks, because everyone learns differently – hopefully you’ll find a tutorial that teaches SwiftUI in a way that works great for you.

The 100 Days of SwiftUI

If you're new to app development, the fastest and easiest way to learn SwiftUI is using my free online course the 100 Days of SwiftUI. Each day guides you through new Swift and SwiftUI techniques to help you build real-world projects, and there are lots of interactive tests to check your knowledge and challenges to help you push your skills further.

Each project is available as an article or as a series of videos, so you can read or watch depending on which you prefer. Best of all, the whole thing is free – just click here to get started.

SwiftUI By Example

I switched across to SwiftUI the day it was announced, and if you were following my many tweets on the topic you’ll know I really fell in love with it.

Shortly after SwiftUI was announced I published an article called [Get started with SwiftUI](/articles/194/get-start...

]]>
Learn SwiftUI with SwiftUI By Example https://www.hackingwithswift.com/articles/195/learn-swiftui-with-swiftui-by-example https://www.hackingwithswift.com/articles/195/learn-swiftui-with-swiftui-by-example Learn SwiftUI online for free or buy the download edition Fri, 14 Jun 2019 12:15:32 +0000 Many people are keen to learn SwiftUI in the fastest way possible, which is why I wrote SwiftUI By Example: a comprehensive, free collection of example code that helps you get started with SwiftUI today.

Not only does SwiftUI By Example walk you through well over 100 common coding problems and solutions, but it also provides a hands-on project that walks you through building a complete app from scratch – and even includes video for every step so you can follow along with me.

I’ve been busy working with SwiftUI since the moment it was launched, and spent most of WWDC at the SwiftUI labs peppering Apple’s engineers with questions – what’s the best way to do X? Why does Y do Z? How does Q work? And more – all so that I could get stuck into the framework as fast as possible.

After only a few days I had already converted six apps from UIKit to SwiftUI, and I’ve converted another 20 since – each time figuring out better and better ways to solve common problems efficiently.

If you want to learn SwiftUI, you’re more than welcome to follow the same path I did: read through all the documentation, watch all the WWDC videos, talk to Apple’s engineers directly, then write several thousand lines of code and refactor it repeatedly until it’s polished.

Alternatively, you can just read my book SwiftUI By Example. It is quite literally the collection of all my findings so far: all the problems I hit and how they were solved, all the questions I asked and the answers I received, and all the code I wrote and how it helps you get ahead now rather than repeating all the time and effort I already put in.

Apart from one being online and the other ...

]]>
Get started with SwiftUI https://www.hackingwithswift.com/articles/194/get-started-with-swiftui https://www.hackingwithswift.com/articles/194/get-started-with-swiftui Hands-on code to help you get moving fast. Tue, 04 Jun 2019 16:10:26 +0000 SwiftUI is Apple's incredible new user interface framework for building apps for iOS, macOS, tvOS, and even watchOS, and brings with it a new, declarative way of building apps that makes it faster and safer to build software.

If you're already using UIKit there's a bit of a speed bump at first because we’re all so programmed to think in terms of UIKit’s flow, but once you’re past that – once you start thinking in the SwiftUI mindset – then everything becomes much clearer.

At the launch of SwiftUI at WWDC19, Apple described it as being four things:

  • Declarative, meaning that we say what we want rather than how we get there.
  • Automatic, meaning that it takes care of many things we had to do by hand previously.
  • Compositional, meaning that we build small things and combine them together into larger things.
  • Consistent, meaning that we don’t see strange fault lines between Swift and Objective-C like we did previously, or very old APIs mixed up with very new ones.

Having now written tens of thousands of lines of code with SwiftUI I can tell you they missed one important point off: concise. Your SwiftUI code will be maybe 10-20% of what your UIKit code was – almost all of it disappears because we no longer repeat ourselves, no longer need to handle so many lifecycle methods, and more.

Let’s dig in to how SwiftUI works…

 

  • Update: I've released a massive, free guide to SwiftUI here: SwiftUI by Example – it contains a huge number of code samples and solutions for common SwiftUI problems, plus a long video showing you how to build your first complete project.
  • You can also now follow my free 100 Days of SwiftUI curriculum to learn SwiftUI in a hands-on way.

 

What is a View?

In SwiftUI, View is more or less what we had with UIView, with two major differences:

  1. It’s a protocol rather than a class, so we don’t get stuck in inheritance ...
]]>
What’s new in iOS 13? https://www.hackingwithswift.com/articles/193/whats-new-in-ios-13 https://www.hackingwithswift.com/articles/193/whats-new-in-ios-13 All the major iOS developer and API changes announced at WWDC19 Tue, 04 Jun 2019 03:47:29 +0000 iOS 13 introduces a vast collection of changes for developers: new APIs, new frameworks, new UI changes, and more. Oh, and Marzipan! Or should that be Project Catalyst now? And dark mode! And iPadOS! And, and, and…!

Rather than try to sum up everything that’s changed in one article, instead this article is here as a jumping-off point into many smaller articles – I’m writing individual mini-tutorials about specific changes, publishing them on a rolling basis and adding links here.

Let’s start with the big stuff…

SwiftUI: a new way of designing apps

Xcode 11 introduced a new way of designing the user interface for our apps, known as SwiftUI. For a long time we’ve had to choose between the benefits of seeing our UI in a storyboard or having a more maintainable option with programmatic UI.

SwiftUI solves this dilemma once and for all by providing a split-screen experience that converts Swift code into a visual preview, and vice versa – make sure you have macOS 10.15 installed to try that feature out.,

See my full article Swift UI lets us build declarative user interfaces in Swift for more information.

UIKit: Dark mode, macOS, and more

At WWDC18 Apple announced a preview of a new technology designed to make it easy to port iOS apps to macOS. This technology – previously known to us by the name “Marzipan” but now Project Catalyst – turns out to mostly be powered by a single checkbox in Xcode that adds macOS as a target for iOS apps, which is helpful because it means it doesn’t take much for most of us to get started.

Note: Shipping iOS apps on macOS using Project Catalyst requires macOS 10.15.

There are, inevitably, a handful of tweaks required to make your app work better...

]]>
What's new in Xcode 11 https://www.hackingwithswift.com/articles/192/whats-new-in-xcode-11 https://www.hackingwithswift.com/articles/192/whats-new-in-xcode-11 SwiftUI, Project Catalyst, Swift Package Manager integration, and more Mon, 03 Jun 2019 20:50:56 +0000 Xcode 11 is another major step towards refreshing our veteran IDE piece by piece, this time including support for UIKit apps on macOS (previously known widely as “Marzipan”), easier creation of user interface code through SwiftUI, Swift Package Manager support for iOS targets, significantly improved iOS simulator performance, and some slick improved to the code editing experience – there’s a mini-map now!

In this article I’m going to walk you through what’s changed so you can see for yourself. Note that for the full experience you should be running macOS 10.15.

Swift 5.1 is here!

Only a few months after Swift 5.0 shipped, Swift 5.1 has landed another raft of improvements to the language.

I’ve detailed these changes extensively in my article what’s new in Swift 5.1, along with releasing lots of videos that highlight individual features:

I’m expecting Swift 5.1 to ship as final alongside the Xcode 11 GM, which based on previous years is going to arrive in September. Hopefully soon we’ll start to get guidance on when to expect Swift 5.2 – as well as what to expect in there – but although it’s only a number I hope we’ll see Swift major releases sync up with Xcode major releases next year!

SwiftUI opens a bold new era

I’ve lost track of how many rumors there were about a declarative UI framework in the making somewhere deep inside Apple, but now it’s landed and Swift...

]]>
SwiftUI lets us build declarative user interfaces in Swift https://www.hackingwithswift.com/articles/191/swiftui-lets-us-build-declarative-user-interfaces-in-swift https://www.hackingwithswift.com/articles/191/swiftui-lets-us-build-declarative-user-interfaces-in-swift Lots of free SwiftUI tutorials are already available. Mon, 03 Jun 2019 19:29:58 +0000 Although storyboards and XIBs have served us well, they aren’t to everyone’s liking – they can be messy to use with source control, they make it hard if not impossible to move between code and visual layouts, and they rely on a flaky system of connections using actions and outlets.

SwiftUI sweeps all that away in several important ways:

  1. There’s a new declarative UI structure that defines how our layouts look and work.
  2. Updating the UI preview automatically generates new Swift code, and changing the Swift code updates the UI preview.
  3. Any bindings in the Swift – e.g. outlets and actions, effectively – are now checked at compile time, so there’s no more risk of UI failing by surprise at runtime.
  4. Although it uses controls from UIKit and AppKit behind the scenes, it sits on top of them, effectively making the underlying UI framework an implementation detail rather than something we care specifically about it.

 

How to use SwiftUI

I am busy pushing SwiftUI as hard as I can with Xcode 11, while also speaking to Apple engineers here at WWDC, so as I learn best practices from them I’ll be trying to distill them down to tutorials to help you get up to speed as fast as possible – watch this space!

There are some gotchas

Before you dive headfirst into SwiftUI, there are two important provisos to be aware of. First, it’s Swift only – you can’t use SwiftUI from Objective-C, which isn’t much of a surprise given the name. Although I’m still poking around, I expect this year’s release to not give us the full range of power we’re used to, so existing iOS developers will probably want to stick to the regular code they know until SwiftUI matures. I’ll know more once I’ve spent more time with the tool, but given that this is an early release I would imagine Apple prefers to play it safe...

]]>
The 15 Best WWDC Videos of All Time https://www.hackingwithswift.com/articles/190/the-best-wwdc-videos-of-all-time https://www.hackingwithswift.com/articles/190/the-best-wwdc-videos-of-all-time Auto Layout, algorithms, Crusty, and more Mon, 03 Jun 2019 07:49:49 +0000 Every year Apple presents its Worldwide Developer Conference (WWDC), giving us five days of keynotes, sessions, and labs that bring the world up to speed with the latest developments across all Apple platforms.

But with five days and multiple simultaneous tracks, it can be hard to know which sessions deserve special attention. So, with the help of many friends on the internet I put together a list of what I consider to be the best WWDC videos of all time.

Before I start, there are some rules:

  1. The video must still be relevant. That doesn’t necessarily mean it must be about Swift, but any killer talks about things Apple has replaced, discontinued, or sidelined, weren’t considered for this list.
  2. No keynotes, and no “What’s new in…”. Yes, I know they are awesome, particularly the keynote where Swift was introduced, but it wouldn’t be fair.
  3. If similar content from an older video was presented in a newer video, the newer video is included.
  4. “Best” is subjective. I’ve tried to pick talks that I know contain lots of useful information so you can learn something valuable. If you disagree you’re welcome to tweet me.
  5. I’ve attempted to mark each talk as being Beginner, Intermediate, or Advanced. This is also subjective – it’s just to give you a rough guide.

Without further ado, here are what I consider to be the best WWDC videos of all time…

15. Embracing Algorithms

Year: 2018   Difficulty: Advanced   Watch here

It’s rare for Apple to get right down to the fundamentals of computer science, but when they do it they do it well. This talk uses extensive code examples to give clear, practical guidance to help you write more efficient code – if you’ve seen things like O(n) in the Swift documentation and wondered what it means in practice, this talk is for you.

14. Prototypin...

]]>
Interview: Dave Verwer https://www.hackingwithswift.com/articles/189/interview-dave-verwer https://www.hackingwithswift.com/articles/189/interview-dave-verwer We talk about iOS Dev Weekly, app review times, developer health, and more. Tue, 28 May 2019 19:39:58 +0000 There are lots of newsletters for Apple developers to read, but if there’s one that stands out above the rest – both for its longevity but also its enduring popularity – it’s iOS Dev Weekly. Behind that newsletter is Dave Verwer, but he also runs iOS Dev Directory and iOS Dev Jobs, while also traveling the world speaking at iOS events.

I caught up with Dave ahead of WWDC to talk about his iOS journey so far, what makes iOS Dev Weekly tick, and why the future is brighter than ever for folks building native iOS apps…

Hacking with Swift: Although I think you're best known for running iOS Dev Weekly, your first project for the iOS developer community was App Review Times. How do you think such public insight to app review helped shape our expectations?

“If you were working with clients it was almost impossible to manage their expectations.”

Dave Verwer: It’s sometimes hard to remember how frustrating that delay was in the early years of the App Store. It wasn't even the length of the delay that was the main problem, it was more that you could wait one week for several reviews in a row, but then sometimes it could take 3 weeks! That was frustrating enough working on your own apps, which is mostly what I was doing at the time, but if you were working with clients it was almost impossible to manage their expectations.

HWS: Do you think the site applied some pressure on Apple to do better?

DV: It’s hard to say. They certainly knew about the site, but the fact that review times stayed so long for years means they probably weren’t feeling a whole lot of pressure about it. When Phil Schiller took over responsibility for the App Store in 2015, review times dropped quickly so I think it’s probably more that he just thought that was a priority, and so he asked his team to fix it. Did App Review Times help him decide that was a priority? Maybe, but pr...

]]>
Improving your Swift code using value objects https://www.hackingwithswift.com/articles/188/improving-your-swift-code-using-value-objects https://www.hackingwithswift.com/articles/188/improving-your-swift-code-using-value-objects They’re like super-charged value types. Thu, 23 May 2019 19:46:21 +0000 What if I told you that you can write Swift code that’s easier to understand, easier to test, has fewer bugs, and is more secure, all with one simple change?

No, this isn’t a scam, and in fact it’s using a time-tested technique called value objects. These have some similarities with value types but aren’t the same thing as you’ll see. Even better, you’ve already used at least one common type of value object, so hopefully the advantages will be clear pretty quickly.

What is a username?

Take a look at the following example Swift code and see if you spot a commonality:

func authenticate(user: String) { }
func purchase(product: String, quantity: Int) { }
func sendEmail(to recipients: [String]) { }

Yes, one obvious commonality is that all three are functions without any code inside, but there’s something else: all three use primitive types for their parameters.

Primitive types are things like strings, integers, and Booleans. In Swift they are all value types, which means they always have one unique owner rather than being shared, which itself is a great way to reduce complexity in our code. However, does an integer accurately represent the number of products in a purchase? Does a string accurately represent usernames?

The answer is almost certainly no. There’s a good joke by Bill Sempf that goes: “A QA Engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljknesv.” The point here is that quantities of a product need to fall within a certain range:

  • Negative values don’t make sense.
  • A zero quantity isn’t a purchase.
  • Very large quantities are likely to be invalid – unless you’re a store that sells individual peas!

As for usernames, you can imagine how the start of the authenticate(user:) method might look:

func authenticate(user: String) {
    // make sure usernames are at least three characters
    guard user.trimmingCharacters(in: .whitesp...
]]>
How to use opaque return types in Swift 5.1 https://www.hackingwithswift.com/articles/187/how-to-use-opaque-return-types-in-swift-5-1 https://www.hackingwithswift.com/articles/187/how-to-use-opaque-return-types-in-swift-5-1 Power, flexibility, and encapsulation all rolled into one Fri, 10 May 2019 10:11:53 +0000 Swift 5.1 introduces an important new feature into the language called opaque types – types where we’re told about the capabilities of an object without knowing specifically what kind of object it is. This has come about through SE-0244, which is part of a larger roadmap to improve generic functionality in Swift.

At first glance opaque types sound a lot like protocols, but they take the concept of protocols significantly further because they are able to work with associated types, they require the same type to be used internally each time, and they allow us to hide implementation details.

As an example, if we wanted to launch different kinds of fighters from a Rebel base we might write code like this:

protocol Fighter { }
struct XWing: Fighter { }

func launchFighter() -> Fighter {
    XWing()
}

let red5 = launchFighter()

Note: Swift 5.1 no longer requires the return keyword in single-expression functions, so XWing() is the same as return XWing() – you can read more about that here.

Whoever calls that launchFighter() function knows it will return some sort of Fighter but doesn’t know precisely what. As a result, we could add struct YWing: Fighter { } or other types, and have any of them be returned.

But there’s a problem: what if we wanted to check whether a specific fighter was Red 5? You might think the solution is to make Fighter conform to the Equatable protocol so we can use ==. However, as soon as you do that Swift will throw up a particularly dreaded error for the launchFighter function: “Protocol 'Fighter' can only be used as a generic constraint because it has Self or associated type requirements.”

The “Self” part of that error is what is hitting us here. The Equatable protocol has to compare two instances of itself (“Self”) to see whether they are the same, ...

]]>
Take the Hacking with Swift WWDC19 Quiz https://www.hackingwithswift.com/articles/186/wwdc-quiz https://www.hackingwithswift.com/articles/186/wwdc-quiz Think you know WWDC? Prove it! Thu, 18 Apr 2019 14:20:38 +0000 I'm supposed to be busy working on my 100 Days of Swift, but now that all tickets and scholars have been announced for this year's WWDC I thought it was time to do something special.

Below you'll find a range of questions that test your knowledge of Apple's Worldwide Developer Conference. Share your result on Twitter and see if you beat your friends!