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 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 we’ve seen a huge number of free tutorials as articles, YouTube videos, books, and more – it’s safe to say that folks are excited, and are keen to share that excitement with the world!

I’ve been creating lots 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.

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, which outlines the basics of creating views, stacks, lists, and more.

Since then, I’ve produced a huge amount of SwiftUI example code and videos:

More recently I’ve been worki...

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

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 10 more 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 being offline, the two editions are identical. Yes, that means you can learn SwiftUI for free today, all using the online edition – you don’t need to pay anything.

SwiftUI is an extraordinarily exciting new technology that is going to completely change the way we ...

]]>
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 As I write this I’ve had Xcode 11 beta for almost 24 hours, and in that time I’ve built maybe six example apps using SwiftUI.

I’m not going to lie: it’s quite the mental 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.

In its launch, Apple described SwiftUI 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 built several apps 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.

 

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 problems.
  2. Our view must always return one view to render. That view might internally contain other views, but it’s still just one parent view going back.

Apple’s default sample code gives us this view:

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
...
]]>
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 on the desktop – as I figure out best practice from folks here at WWDC I’ll add links below!

Also, iOS 13 brings us a system-wide dark mode, which has been requested for as many years as I c...

]]>
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!