Hacking with Swift News, tips, and tutorials from Hacking with Swift https://www.hackingwithswift.com/articles/rss (c)2020 Paul Hudson https://www.hackingwithswift.com/favicon-96x96.png Hacking with Swift https://www.hackingwithswift.com/articles/rss Learn essential Swift in one hour https://www.hackingwithswift.com/articles/242/learn-essential-swift-in-one-hour https://www.hackingwithswift.com/articles/242/learn-essential-swift-in-one-hour Here’s the least you need to know to get started with Swift. Fri, 15 Oct 2021 21:23:01 +0000 In this article I’m going to introduce you to the fundamentals of the Swift programming language in about one hour.

This article is aimed at two kinds of people: folks who have completed the introduction to my 100 Days of SwiftUI course and are looking for a quick review, and folks who are experienced with other languages and want to transfer their skills over to Swift.

We’re going to move fast because this is designed to be a primer – if you find yourself struggling to understand something, visit the 100 Days of SwiftUI to complete the longer, more detailed introduction there.

Let’s get to it!

Creating constants and variables

Swift can create constants and variables, but constants are generally preferable.

Use this to create then change a variable string:

var name = "Ted"
name = "Rebecca"

If you don’t want to change a value, use a constant instead:

let user = "Daphne"

The print() function is helpful for learning and debugging, and shows some information about a variable:

print(user)

Strings

Swift’s strings start and end with double quotes:

let actor = "Tom Cruise"

And they work great with emoji too:

let actor = "Tom Cruise 🏃‍♂️"

If you want double quotes inside your string, place a backslash before them:

let quote = "He tapped a sign saying \"Believe\" and walked away."

If you want a string that spans multiple lines, start and end with three double quotes, like this:

let movie = """
A day in
the life of an
Apple engineer
"""

Swift provides many useful properties and methods for strings, including .count to read how many letters it has:

print(actor.count)

There are also hasPrefix() and hasSuffix(), which lets us know whether a string starts or ends with specific letters:

print(quote.hasPrefix("He"))
print(quote.hasSuffix("Away."))

Important: Strings are case-sensitive in Swift, so ...

]]>
My favorite new Swift API from iOS 15 https://www.hackingwithswift.com/articles/241/how-to-fetch-remote-data-the-easy-way-with-url-lines https://www.hackingwithswift.com/articles/241/how-to-fetch-remote-data-the-easy-way-with-url-lines AsyncSequence and effectful read-only properties combine to make something beautiful. Thu, 19 Aug 2021 13:11:29 +0000 WWDC21 came packed with lots of new features for Swift, SwiftUI, Foundation, and more, but in all the WWDC videos I’ve watched only one made me do a double take – I had to rewind and rewatch it just to make sure I hadn’t misheard.

The feature sounds simple, but makes for quite astonishing code: it’s the lines property on URL, which downloads and returns lines of text from a URL as they are fetched. Internally this builds on a huge amount of functionality, not least effectful read-only properties and AsyncSequence, and the end result is quite remarkable in terms of its simplicity.

In its simplest form this means we can access string data directly from a URL, either local or remote. This is perfect for simpler APIs that vend data line by line, such as plain-text files or CSV – Swift even keeps the connection open as long as necessary so new data can be streamed in as needed.

Trying it out with SwiftUI

Using this API, we could write a small app to fetch a collection of quotes from a server and display them in a list, all using hardly any code:

struct ContentView: View {
    @State private var quotes = [String]()

    var body: some View {
        List(quotes, id: \.self, rowContent: Text.init)
            .task {
                do {
                    let url = URL(string: "https://hws.dev/quotes.txt")!

                    for try await quote in url.lines {
                        quotes.append(quote)
                    }
                } catch {
                    // Stop adding quotes when an error is thrown
                }
        }
    }
}

Perhaps you can see what made me do the double take in the first place – I was surprised to be able to access lines directly on a URL, rather than routin...

]]>
Hacking with Swift Live 2021 raises $61,000 for charity https://www.hackingwithswift.com/articles/240/hacking-with-swift-live-2021-raises-61000-for-charity https://www.hackingwithswift.com/articles/240/hacking-with-swift-live-2021-raises-61000-for-charity Make apps, make friends, make a difference. Thu, 05 Aug 2021 14:42:37 +0000 Hacking with Swift Live 2021 just finished, delivering three days of tutorials and workshops on all the major concurrency changes to Swift, the many improvements for SwiftUI, and more. Even better, because all our profits go to charity we were able to donate $61,000 to an incredible cause – everyone got to take their Swift skills forward, meet new friends, and make a real difference outside our community.

Just like last year, we donated all our profits to Special Effect, who help to bring joy, creativity, and confidence into the lives of people with disabilities. With the pandemic somehow still raging many charities continue to have a hard time raising funds, so we’re glad to play a part in helping continue their important work.

The feedback so far has been overwhelmingly positive, and I’m really grateful to everyone to bought a ticket, our individual sponsors, the many folks who bought diversity tickets, and of course our corporate sponsors.

This year we were lucky enough to have two platinum sponsors:

  • DuckDuckGo has a private search engine, a privacy-focused browser app, and a privacy browser extension, so I think you know exactly what their #1 priority is!
  • Instabug’s tools can help you find and fix bugs faster thanks to comprehensive crash reporting and performance metrics.

We also had three silver sponsors:

  • Backbase are building a software platform to help banks move faster in a digital-first world.
  • Emerge analyses your code to provide insights to help make your app size smaller, and even generates size diffs on every PR!
  • Bitrise offers fast, flexible, and scalable continuous integration and delivery for app developers, offering dozens of integrations with well-known tools.

Each of those sponsors went out of their way to support our event, not only making significant charity donations but al...

]]>
WWDC21: Wrap up and recommended talks https://www.hackingwithswift.com/articles/239/wwdc21-wrap-up-and-recommended-talks https://www.hackingwithswift.com/articles/239/wwdc21-wrap-up-and-recommended-talks Packed sessions, digital lounges, and a look forward to 2022. Sun, 20 Jun 2021 21:39:38 +0000 Apple’s annual event is done and dusted for another 12 months, featuring a major raft of updates for all platforms, plus Swift, SwiftUI, UIKit, and more. But perhaps just as importantly, this year also featured a number of improvements to the conference format itself, and it seems increasingly clear that we cannot go back to the old WWDC format again.

In this article I’ll go over how I thought the event went, pick out the talks I enjoyed the most and would recommend you watch, highlight some of my favorite community events, and put forward a handful of suggestions for how WWDC22 might look.

And away we code!

WWDC20 took place during a global pandemic, and WWDC21 also took place during a global pandemic. But this year Apple was prepared – perhaps they had some plans in place for an in-person WWDC just in case things had improved by the start of the year, but it seems clear this year a great deal of work had gone into making WWDC work better as an event for everyone.

Even from the very first keynote video it was obvious this year Apple had doubled down on the production quality for their videos. Yes, Craig’s teleportation effect somewhat stole the show, but also we saw carefully orchestrated presenter handovers across a wide team and a variety of impressive CGI overlays that brought the launch day to life.

A woman talking in front of the Swift logo. This is Susan Prescott, introducing a segment on developer technologies.

But the keynote did a lot to set the stage for the week. Yes, Craig called developers “the heart and soul of WWDC” – I mean, it’s right there in the name – but things really kicked off when Ted Kremenek took over presenting. I can’t imagine I was alone in feeling my pulse pick up when that happened, because Apple only shows code during the keynote when they mean business. Unsurprisingly this segment focused on concurrency, and even if you’ve only managed to watch a few of the videos from WWDC21 you’ll almost ...

]]>
How to document your project with DocC https://www.hackingwithswift.com/articles/238/how-to-document-your-project-with-docc https://www.hackingwithswift.com/articles/238/how-to-document-your-project-with-docc Markdown-powered documentation is now just a click away. Sun, 13 Jun 2021 15:22:35 +0000 DocC is Apple’s new tool for building beautiful, interactive, and native-feeling documentation right from your code, and it integrates smoothly into both Xcode and the web.

In this article I’m going to walk you through the fundamentals of using it in two different ways: building documentation for a framework, and adding articles that provide more depth. Along the way, you’ll see some places where DocC works brilliantly, and also some places where it doesn’t really work like I’d expect at all. And that’s okay – it’s only the initial release, after all.

Before I start, though, there are some basics:

  • You need to have Xcode 13 installed in order to have access to DocC.
  • It supports only Swift at this time. They have already received requests to add Objective-C support, and in the long term I hope they’ll add support for other languages too.
  • In case you were curious, DocC is short for “Documentation Compiler”, and it’s pronounced with two equally stressed syllables – “Doc-See” as opposed to “doxy”.
  • Xcode is packed with lots of major new features – it’s another real stand out year, and I hope the team are feeling really proud. You can find out more in my article What’s new in Xcode 13.

Please keep in mind I’m using Xcode 13 beta 1, so it’s all early days at this point – I expect DocC to get polished up a lot before the final release later this year.

First, what DoC is not

The first thing I did when trying out DocC is what I expect most app developers would do: I opened up one of my projects to see what DocC would make of it. In my case, that was Unwrap – it’s a good size of project with various dependencies, and matches the kind of thing many app developers will be working with.

If you want to try this in your own app project, just go to the Product menu and choose Build Documentation. It might take a minute or two to ...

]]>
The Complete Guide to SF Symbols https://www.hackingwithswift.com/articles/237/complete-guide-to-sf-symbols https://www.hackingwithswift.com/articles/237/complete-guide-to-sf-symbols Example code, tips, and techniques for both SwiftUI and UIKit Sun, 13 Jun 2021 08:06:10 +0000 SF Symbols allows us to render a huge and growing variety of icons inside our apps, and every year it gets bigger – not only do many more icons get added, but iOS 14 added the ability to render multicolor icons and iOS 15 added the ability to have complete control over individual layers.

In this article I’m going to walk you how to use SF Symbols in your projects, providing code for both SwiftUI and UIKit. Let’s get into it…

Tip: The best way to browse the list of symbols is using Apple’s free SF Symbols app.

How to load an SF Symbol

The simplest thing you’re going to want to do is load a symbol. We’ll be using “star” here, but if you’re using the SF Symbols app you can right-click any symbol and choose Copy Name.

In SwiftUI loading an image is done by placing an Image into your view hierarchy using its systemName initializer:

Image(systemName: "star")

In UIKit you need to use UIImage then place it in a UIImageView, like this:

let image = UIImage(systemName: "star")
let imageView = UIImageView(image: image)

How to place SF Symbols next to text

SF Symbols work great when used inside text, particularly when they contain common symbols such as error crosses, check marks, calendars, and similar.

In SwiftUI placing an image next to text is done like this:

Label("Please try again", systemImage: "xmark.circle")

If you want to place it inside the text string, it’s better to use string interpolation with Image, like this:

Text("Please press the \(Image(systemName: "calendar")) button")

For UIKit the code is a little more complex because you need to use NSAttributedString and NSTextAttachment to render something into a UILabel, but the same code lets you place the images wherever you want them:

let attachment = NSTextAttachment()
attachment.image = UIImage(systemName: "xmark.circle")

let imageString = NSMutableAttributedString(attachment: attach...
]]>
What’s new in Xcode 13? https://www.hackingwithswift.com/articles/236/whats-new-in-xcode-13 https://www.hackingwithswift.com/articles/236/whats-new-in-xcode-13 Vim keybindings, integrated collaboration, faster version comparison, and more. Thu, 10 Jun 2021 20:22:54 +0000 Xcode 13 arrived at WWDC21 and includes a huge range of new features, improvements, and performance enhancements. In this article I’m going to walk you through all the key changes, so you can get up to speed quickly, but before I start I need to make two things clear:

First, no, I don’t have beta access to Xcode Cloud or the new Swift Playgrounds. Trust me, I wish I did! Both of these things look likely to be significant upgrades for the Swift community, and I’m really keen to try them out at the earliest opportunity.

And second, you might immediately note that Xcode hides your file extensions by default in the project navigator. This seems to mimic your Finder configuration, so if you’re suddenly confused where your file extensions have gone then you can bring them back With This One Weird Tip: go to Xcode’s preferences, select General, then change File Extensions to Show All. I’m going to try sticking with hidden extensions to see how I get on with it.

Anyway, in this article I’ll be talking about the new workflow tools for teams, the new source control features, the new improvements to how we write code, and more – it’s a packed release, so let’s get straight to it.

Source editor improvements

First let’s talk about the source editor, which is where we spend most of our time – this is just the way we type code into Xcode, as opposed to all the main IDE features around it.

When I posted about some of these on Twitter, a bunch of folks replied back saying how Xcode sucks because their personal favorite IDE had these features years ago, and honestly just please pass me by with those kinds of comments – if I wanted to use your IDE I would already be doing so.

So, let’s talk about some major changes to the way we write code in Xcode.

First, if you use a type that isn’t currently available, Xcode can automatically import it for you. So, if you write code like this:

struct ExampleView: View

…then Xcode will...

]]>
What’s new in SwiftUI for iOS 15 https://www.hackingwithswift.com/articles/235/whats-new-in-swiftui-for-ios-15 https://www.hackingwithswift.com/articles/235/whats-new-in-swiftui-for-ios-15 Visual effects, remote URLs, and cleaned up APIs galore. Tue, 08 Jun 2021 06:52:24 +0000 Expectations were always going to be high for SwiftUI this year, but the team didn’t disappoint – they’ve shipped a massive collection of improvements and features, including a new AsyncImage view for loading remote images, swipe actions for list rows, pull to refresh, plus shorter, simpler APIs for common uses. Alongside huge improvements to Swift itself (see What's new in Swift 5.5 for more on that), this is another significant leap forward for SwiftUI and I’m really keen to dive in.

Please keep in mind that these changes are very new – I'm pushing it as hard as I can, experimenting, refining, sharing, and learning all at the same time. If you have any feedback, please tweet me @twostraws.

You can watch the video below, or scroll down for links to articles.

The big stuff

More welcome improvements

]]>
Hacking with Swift+ turns 1! https://www.hackingwithswift.com/articles/234/hacking-with-swift-plus-turns-1 https://www.hackingwithswift.com/articles/234/hacking-with-swift-plus-turns-1 New features include ad-free browsing, online books, and more. Tue, 01 Jun 2021 22:21:42 +0000 One year ago today I launched Hacking with Swift+, and already I’ve released over 130 articles and videos covering advanced Swift, SwiftUI, special effects, algorithms, and so much more – it’s been incredible, and I’m really grateful for everyone who subscribed. But I’m not resting on my laurels.

Six months ago I announced that everyone who subscribed for at least a year would get exclusive free gifts mailed to them wherever they lived in the world, and three months ago I added all the videos from Hacking with Swift Live 2020 as another bonus.

Today I’m really pleased to reveal the next set of enhancements:

  • All Hacking with Swift+ subscribers can now browse the whole site with no advertising – that means no sponsor text in the page, no fixed gray bar along the top of articles, and no “buy our books” sidebar on the right. Instead, every page on the site is wider and more streamlined for an optimized reading experience.
  • There’s a new private forum exclusively for Hacking with Swift+ subscribers to ask question questions and chat.
  • I’ve started the process of adding chapter markers to all the Hacking with Swift+ videos. This will take some time to complete, but work has already begun.
  • All Hacking with Swift+ subscribers can enjoy a 20% discount on the download editions of my books and bundles, available year round.

All that is on top of the existing benefits of subscribing.

But we can do better!

I’ve seen some other sites offer enhanced subscriptions that include online access to their books, charging a lot more for the privilege.

That isn’t how I work.

I realized some time ago that as long as I was making enough money to be happy, I didn’t need to earn more – that’s part of the reason I run so many charity events, give away books to folks who need them, and publish so much free content.

So I set out to make a Hacking with Swift+ subscription that gave folks my books to read online without having to break the bank. Obv...

]]>
What's new in Swift 5.5? https://www.hackingwithswift.com/articles/233/whats-new-in-swift-5-5 https://www.hackingwithswift.com/articles/233/whats-new-in-swift-5-5 Async/await, actors, throwing properties, and more! Fri, 28 May 2021 11:49:34 +0000 Swift 5.5 comes with a massive set of improvements – async/await, actors, throwing properties, and many more. For the first time it’s probably easier to ask “what isn’t new in Swift 5.5” because so much is changing.

In this article I’m going to walk through each of the changes with code samples, so you can see how each of them work in practice. This is the first time so many huge Swift Evolution proposals has been so tightly interlinked, so although I’ve tried to organize these changes in a cohesive flow some parts of the concurrency work only really make sense once you’ve read through several proposals.

Async/await

SE-0296 introduces asynchronous (async) functions into Swift, allowing us to run complex asynchronous code almost is if it were synchronous. This is done in two steps: marking async functions with the new async keyword, then calling them using the await keyword, similar to other languages such as C# and JavaScript.

To see how async/await helps the language, it’s helpful to look at how we solved the same problem previously. Completion handlers are commonly used in Swift code to allow us to send back values after a function returns, but they had tricky syntax as you’ll see.

For example, if we wanted to write code that fetched 100,000 weather records from a server, processes them to calculate the average temperature over time, then uploaded the resulting average back to a server, we might have written this:

func fetchWeatherHistory(completion: @escaping ([Double]) -> Void) {
    // Complex networking code here; we'll just send back 100,000 random temperatures
    DispatchQueue.global().async {
        let results = (1...100_000).map { _ in Double.random(in...
]]>
Reimagining Hacking with Swift https://www.hackingwithswift.com/articles/232/reimagining-hacking-with-swift https://www.hackingwithswift.com/articles/232/reimagining-hacking-with-swift With your help things can get better. Fri, 07 May 2021 14:54:05 +0000 Yesterday I wrote a long article called Reimagining Apple’s documentation, in which I wrote down a variety of ways I'd love to see Apple's developer documentation evolve and improve in the future. Although it was written with nothing but appreciation in mind, the article was effectively me telling other people how to do their job – other people, let's not forget, who are already working very hard to deliver the best they can for us.

Anyway, in that article I said, “I need to acknowledge that there are a whole bunch of ways I could make my own site better,” before launching off into a long rant about Apple's site. Well, let’s focus on Hacking with Swift, because if I’m going to look at Apple’s documentation output in the cold light of day I should do the same for my own site.

Where my work is today

Hacking with Swift is visited by over 700,000 unique visitors every month, serving up over 5,000,000 page views – all at the same time as me running a YouTube channel with almost 60,000 subscribers, writing a newsletter with almost 40,000 readers, and delivering talks at conferences. Every single day people get in touch to thank me for an article or video, to ask questions, to suggest new topics, and more, and I’ve lost track of how many people have said they got a job thanks to my work.

I also work hard to make sure I use what platform I have to help people outside our community too, whether that’s through Swift for Good raising money for Black Girls Code, Hacking with Swift Live raising money for Special Effect, my SwiftUI birthday livestream raising money for folks who are sleeping rough, my iOS Accelerator workshop raising money for my kids’ school, or other efforts.

Honestly, that’s great. It’...

]]>
Reimagining Apple’s documentation https://www.hackingwithswift.com/articles/231/reimagining-apples-documentation https://www.hackingwithswift.com/articles/231/reimagining-apples-documentation Example code, faster navigation, and goodbye to No Overview Available. Thu, 06 May 2021 16:11:40 +0000 For a number of years my #1 WWDC wish was that Apple would do something to dramatically rethink its approach to developer documentation. I still hope WWDC21 will be The Year When Something Big Happens To Apple’s Documentation, but rather than just wave vaguely and say “I want better docs” I figured I’d write down some specific thoughts that have been rattling around in my head.

I have a simple mental metaphor for what I want, which is this: what would happen if the hardware team who designed iPhones and iPads were asked to build developer documentation?

I don’t mean “make them describe thousands of APIs,” but instead I mean their mentality – the primary reason most of us buy so many Apple devices is because they are loved down to the micron level. Every tiny part of my iPhone, my iPad, my Apple Watch, and more has been thought about and made as good as they can possibly make it, from the screen, to the audio, to the battery, and beyond. The result is that the finished devices just feel fantastic even many years after they were released.

So I use that as my yardstick: what would magical documentation look like?

I’m going to outline my answers below, but honestly the conclusions won’t surprise anyone: getting fantastic, world-leading developer documentation isn’t about fancy new approaches to tutorials or interactive experiences, but almost entirely about finding the fastest, simplest ways to solve developer problems effectively.

TL;DR

Short on time? Fine – here’s the bulleted list of what I wish would change:

  • The top 500 most popular APIs (measured by page views) should have example code attached, ideally several examples with headers clearly marking what problem is being solved.
  • The top 100 most popular APIs should get either a screenshot or a video showing exactly how it works and what the result is.
  • Any place where header files have documentation comments and their matching online documentation is “No overview available” should have the hea...
]]>
How to Become an iOS Developer in 2021 https://www.hackingwithswift.com/articles/230/how-to-become-an-ios-developer https://www.hackingwithswift.com/articles/230/how-to-become-an-ios-developer The skills, resources, and networking that will get you to your goal Wed, 31 Mar 2021 20:37:46 +0000 In this article I want to walk you through what I think it takes to become an iOS developer in 2021. I’m aiming this squarely at two groups of people: absolute beginners to Swift – folks who have never built anything for iOS before – and also so-called false beginners, who are folks who might have tried to learn Swift before but never really reached their goal of getting a full-time job.

Regardless of what level you are right now, the goal here is the same: getting you in the right position to apply for a junior iOS developer role at a company.

We’re going to look at the skills you should be learning, the courses you can take, how to get connected to the community, common mistakes folks make, and more, and best of all everything I’ll talk about will be completely free so you won’t need a penny to follow along.

Seriously, too many people think spending a ton of money is the fast track to reaching their dream job, when really the most important things are determination and willpower. And here’s a hint for you: if you’re already thinking you want to skip ahead in this article, maybe you should consider working on your willpower!

There are 7 sections to this article:

  1. Core skills you absolutely need to know to get a job.
  2. Extension skills that are nice to have – the ones that will set you apart from the pack, if you have the time to learn them
  3. Common mistakes people make when they are trying to learn.
  4. Resources you can use to learn Swift that are completely free.
  5. How you can connect to the iOS development community.
  6. An idea of how long it will take to reach your goal.
  7. Preparing to apply for your first job
  • This article is also available as a video if you prefer. The content is the same, so use whichever is easiest for you.

What are the core skills you need to be an iOS developer?

What is the absolute minimum set of skills you need to get a job in iOS development? I think there are five things in total:

  1. S...
]]>
24 Quick Xcode Tips https://www.hackingwithswift.com/articles/229/24-quick-xcode-tips https://www.hackingwithswift.com/articles/229/24-quick-xcode-tips Write code faster, build better tests, and navigate around projects more efficiently. Fri, 12 Feb 2021 22:02:25 +0000 Xcode is a huge program, and if you can learn one or two new tips that help you work more effectively you can save hours of time every week.

In this article I want to walk you through 24 quick Xcode tips that help you write code faster, build better tests, and navigate around large projects more efficiently – there’s something for everyone!

  • This article is also available as a video if you prefer. The content is the same, so use whichever is easiest for you.

1. Generating class initializers

Swift can synthesize memberwise initializers for structs, but not for classes. Fortunately, Xcode can generate the code for us: select your class name, then go to the Editor menu and choose Refactor > Generate Memberwise Initializer. Done!

2. Environment overrides

When building software, it’s important to make sure your app works for everyone. One great way to do that is with Xcode’s environment overrides panel, which lets you adjust Dynamic Type size, accessibility options, and appearance all in one place.

3. Selecting blocks of code

You probably already know that you can click after any open { or close } brace to have Xcode highlight its matching brace, but another useful tip is that you can double click a brace to select the entire block of code it contains.

4. Checking our spelling

Xcode can check if your spelling is correct, and it even understands that camelCaseNames should be treated as separate words. Go to the Edit menu and choose Format > Spelling and Grammar > Check Spelling While Typing, and Xcode will check your code for typos.

5. Fixing all issues

If you have a Swift file with many errors, you can use Xcode’s fix-its to try to correct them one by one. But a faster way is to go to the Editor menu and choose Fix All Issues to apply fix-its all at once. (Make sure and double-check which changes were made!)

6. Deleting search results

When you search using Xcode’s find navigator, you can click to v...

]]>
What’s new in Swift 5.4? https://www.hackingwithswift.com/articles/228/whats-new-in-swift-5-4 https://www.hackingwithswift.com/articles/228/whats-new-in-swift-5-4 Multiple variadic parameters, improved implicit member syntax, result builders, and more! Tue, 02 Feb 2021 15:35:14 +0000 Swift 5.4 brings with it some huge compilation improvements, including better code completion in expressions with errors and big speed ups for incremental compilation. However, it also adds some important new features and refinements, so let’s dig into them here…

Improved implicit member syntax

SE-0287 improves Swift’s ability to use implicit member expressions, so rather than just having support for exactly one single static member you can make chains of them.

Swift has always had the ability to use implicit member syntax for simple expressions, for example if you wanted to color some text in SwiftUI you could use .red rather than Color.red:

struct ContentView1: View {
    var body: some View {
        Text("You're not my supervisor!")
            .foregroundColor(.red)
    }
}

Prior to Swift 5.4 this did not work with more complex expressions. For example, if you wanted your red color to be slightly transparent you would need to write this:

struct ContentView2: View {
    var body: some View {
        Text("You're not my supervisor!")
            .foregroundColor(Color.red.opacity(0.5))
    }
}

From Swift 5.4 onwards the compiler is able to understand multiple chained members, meaning that the Color type can be inferred:

struct ContentView3: View {
    var body: some View {
        Text("You're not my supervisor!")
            .foregroundColor(.red.opacity(0.5))
    }
}

Multiple variadic parameters in functions

SE-0284 introduced the ability to have functions, subscripts, and initializers use multiple variadic paramete...

]]>
Which SwiftUI property wrapper to choose in any situation https://www.hackingwithswift.com/articles/227/which-swiftui-property-wrapper https://www.hackingwithswift.com/articles/227/which-swiftui-property-wrapper Decide which property wrapper is the right choice for your needs. Wed, 27 Jan 2021 17:51:44 +0000 SwiftUI uses property wrappers to understand how we create and store data in our views, but if you need helping choosing which property wrapper is right for you I've made a tool to help. To find the right property wrapper for you, answer the questions below 🚀

1. Are you storing a struct, an enum, or a class?

I want to store a struct or an enum.

2. Will the value change over time?

Yes, it will change as my app runs.

3. Are you creating the value in your view, or will it be passed in from somewhere else?

I'll be creating the value locally in my view.

4. Is the property being used to track an active user gesture?

Yes, this is for a gesture.

You should use the @GestureState property wrapper, like this:

@GestureState private var dragAmount = CGSize.zero

Although you could also use @State for this purpose, @GestureState is significantly more efficient.

You can learn more about the @GestureState property wrapper here: What is the @GestureState property wrapper?

No, this is just a regular value.

You should use the @State property wrapper, like this:

@State private var username = "Taylor"

Technically there's nothing stopping y...]]> 5 Steps to Better SwiftUI Views https://www.hackingwithswift.com/articles/226/5-steps-to-better-swiftui-views https://www.hackingwithswift.com/articles/226/5-steps-to-better-swiftui-views Learn to make your SwiftUI views smaller, simpler, and more reusable. Wed, 27 Jan 2021 11:57:00 +0000 As SwiftUI projects grow more complex, it’s common to find your views get larger and larger as you cram more functionality into them. In this article I’ll walk you through the underlying problem, and demonstrate five steps you can take to make your views simpler, smaller, and smarter – all demonstrated using a real SwiftUI project, so you have actual code to follow along.

You can get the project source code, including both before and after versions, from this link.

  • This article is also available as a video if you prefer. The content is the same, so use whichever is easiest for you.

Still here? Okay, let’s get to it…

What’s the problem?

This is a really challenging time for SwiftUI because at this point we’re kind of past the novelty of SwiftUI itself – we’re used to the idea that we can build user interfaces really fast, we’re used to the idea of tracking state effectively, and we’re used to the idea that we can write layouts that work great on all of Apple’s platforms.

However, although many people are already comfortable with the way SwiftUI works, we are still quite a long way from agreeing best practices. For example, if you have several different ways of solving a problem, we’re still in the process of figuring out which one makes most sense for a given situation.

So, we’re at this strange position where many people are learning SwiftUI and writing lots of it, but the apps we build are growing in size and complexity and as a result are starting to suffer from very similar problems that we faced in UIKit in the early years.

Previously it was common to tackle the long-standing UIKit curse of Massive View Controllers, but in SwiftUI we don’t have view controllers at all – in fact, many would say that the lack of view controllers is the best feature of SwiftUI!

However, we do make a lot of view structs where we cram a lot of functionality. This created a wholl...

]]> Year in review: 2020 https://www.hackingwithswift.com/articles/225/year-in-review-2020 https://www.hackingwithswift.com/articles/225/year-in-review-2020 A brief look back on another year of Hacking with Swift Fri, 01 Jan 2021 22:20:32 +0000 What the heck just happened? 😂

Many people – myself included – had big plans for the year. I wanted to work more on my open source software (Unwrap, Control Room, Sitrep, and more), I wanted to update a whole collection of books to be more focused on SwiftUI, I wanted to write new, shorter books to go alongside SwiftUI By Example, and more.

And then COVID-19 happened.

This meant my kids were home from school for many months, it meant I spent way too much time scrolling through depressing news rather than working, and honestly it meant a lot of the time I struggled to find the willpower to think about – never mind write about – anything.

So, this year turned out quite different from what I had anticipated, but there were still a few highlights…

Advance warning: This is a hugely self-indulgent article talking about what went well – and not so well – in my Hacking with Swift work this year. Hopefully you don’t find it too dull, but I only do it once a year!

Updates, rewrites, and more

This year I published a new, free book called Understanding Swift, which was entirely unlike all the other books I’ve written previously because I wanted each chapter to answer one question. The goal here was to focus firmly on why Swift is the way it is, because there are lots of code samples out there for any given topic but not a great deal of explanation of why features and functionality exists in the first place.

So, you’ll find chapters such as “What the heck are closures and why does Swift love them so much?”, “When should you write throwing functions?”, “How do Swift’s memberwise initializers work?”, and more – all questions that I was commonly asked by folks who were completing the 100 Days of SwiftUI.

I also published [Swift on Sundays Volume 1](h...

]]>
8 Common SwiftUI Mistakes - and how to fix them https://www.hackingwithswift.com/articles/224/common-swiftui-mistakes-and-how-to-fix-them https://www.hackingwithswift.com/articles/224/common-swiftui-mistakes-and-how-to-fix-them Write less code and get more done Fri, 09 Oct 2020 13:29:31 +0000 SwiftUI is a big and complex framework, and although it’s great fun to work with there’s also a lot of scope for making mistakes. In this article I’m going to walk through eight common mistakes SwiftUI learners make, and how to fix them.

Some of these mistakes are simple misunderstandings, and with SwiftUI being so big these are easy to make. Others are about getting a deeper understanding of how SwiftUI works, and still others are more a sign of legacy thinking – sometimes you spend a lot of time writing views and modifiers and don’t take the time to simplify the end result.

Anyway, I’m not going to keep you in suspense about what these eight mistakes are, so here’s a brief summary before we dive into them:

  1. Adding views and modifiers where they aren’t needed
  2. Using @ObservedObject when they mean @StateObject
  3. Putting modifiers in the wrong order
  4. Attaching property observers to property wrappers
  5. Stroking shapes when they mean to stroke the border
  6. Using alerts and sheets with optionals
  7. Trying to get “behind” their SwiftUI view
  8. Creating dynamic views using invalid ranges

If you prefer to watch a video instead, I've got you covered!

Still here? Okay, let’s get to it…

1. Adding views and modifiers where they aren’t needed

Let’s start with one of the most common, which is writing more SwiftUI code than you actually need. This is common partly because it’s often we write a lot of code as we’re figuring out a problem, but it’s easy to forget to clean up that code afterwards. It’s also sometimes a matter of slipping back into old habits, particular if you’ve come from UIKit or other user interface frameworks.

As a starting example, how might you fill the screen with a red rectangle? You might write this:

Rectangle()
    .fill(Color.red)

And honestly that works great – it gets the exact result you want. But half that code isn’t needed, because you can instead just say...

]]>
Hacking with Swift Live 2020 raises $38,000 for charity https://www.hackingwithswift.com/articles/223/hacking-with-swift-live-2020-raises-38000-for-charity https://www.hackingwithswift.com/articles/223/hacking-with-swift-live-2020-raises-38000-for-charity Make apps, make friends, make a difference Thu, 16 Jul 2020 16:55:11 +0000 Hacking with Swift Live 2020 just finished, delivering four days of packed tutorials and workshops walking through all the major new features for SwiftUI, UIKit, and more. Even better, because all our profits go to charity we were able to donate $38,000 to an incredible cause – folks made friends, learned lots of new Swift skills, and made a difference to the wider world.

I’m hugely grateful to everyone who bought a ticket to the event, and the feedback so far has been really positive. Over four days we really got to know each other even though it was a remote event, and it’s amazing to see folks leaving with new friends. Thank you so much for coming!

I’m also really grateful to our two sponsors: Bitrise came back for a second year as platinum sponsor, and several members of their team came along to the event. Instabug also joined as silver sponsor for the first time, and it was great to have them on board.

Both those companies could easily have used that money to show adverts on Google, Twitter, or other services, but they instead chose to make a significant charitable donation in order to support a community conference like this one. Thank you so much!

Just like last year, we donated all our profits to Special Effect, who do remarkable work to help bring joy, laughter, creativity, and confidence into the lives of disabled children and adults. With the pandemic still raging many charities are having a hard time raising funds, so we’re glad to play a part in helping continue their awesome work.

This event wouldn’t have been possible without the help of the organizing team: Chris Rivers, Daniel Leivers, Ian Lockett, and my wife Ildiko. We all work really hard to bring this event to you and don’t get paid a penny – we send everything we can to charity.

So, ...

]]>