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 How to fix slow List updates in SwiftUI https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui Make it faster with this one weird trick! Fri, 10 Jan 2020 14:35:21 +0000 If you have a SwiftUI list with lots of rows, you might find it's really slow to update when you sort or filter those rows – code that should run instantly might take one or two seconds, or if you have lots of items one or two minutes.

I'm going to show you what code causes the problem, then show you the one line of SwiftUI code that fixes it, and finally the most important part: explain why the problem occurs so you aren't just adding code without understanding it.

Let's go to Xcode…

 

Prefer video? The screencast below contains everything in this tutorial and more – subscribe to my YouTube channel for more like this.

 

Our problem code

Here's a concise piece of SwiftUI code that demonstrates our problem:

struct ContentView: View {
    @State var items = Array(1...600)

    var body: some View {
        VStack {
            Button("Shuffle") {
                self.items.shuffle()
            }

            List(items, id: \.self) {
                Text("Item \($0)")
            }
        }
    }
}

There I have a view that has one property, which is an array of 600 integers from 1 to 600.

Inside the body there's a VStack with a Button that shuffles the items every time it's pressed, and a List that shows all the items. Shuffling the array is how we're simulating you changing the items, because it forces the list to update its rows.

If you run that code in the simulator you'll see the button and list of items, and if you press the button you'll see nothing happens – at least at first. If we wait a little longer… boom, the list updates. And if you press the button again, the same thing h...

]]>
Year in review: 2019 https://www.hackingwithswift.com/articles/209/year-in-review-2019 https://www.hackingwithswift.com/articles/209/year-in-review-2019 A brief look back on another year of Hacking with Swift Sun, 29 Dec 2019 17:38:10 +0000 2019 was my busiest year to date: hundreds of new articles, new videos, a conference, an app, a mentoring program, and a whole lot of charity work – I really feel I made the most of my time and position.

Howeer, I usually spend so much time doing the work that I don’t have much time left over to reflect on it all. So, once again I’ve written this Year in Review post to help summarize what I worked on, what results that work had, and what I’m planning for 2020.

As a reminder, this is my full-time job – don’t look at the below and imagine I’m some sort of super-productive genius, because the simple truth is that this is all I do. I don’t have meetings to attend, Jira backlogs to dig through, pull requests to review, and so on; I’m lucky enough that my entire job is exploring Swift development and sharing what I learned with others.

OK, let’s see what happened in 2019…

Publishing my brain

Have you ever been in the middle of a particular project, but had your brain so fizzing with ideas for a side project that you’ve had to stop what you were doing and work on that other thing for a while?

Me too. And I get it for writing a lot – I’m working with Swift all the time, and my brain leaps around between projects, APIs, and even platforms as I’m trying things that have my brain excited and as connections jump out at me. These things keep me up at night sometimes: if I try to sleep without writing them down my brain just stays in gear, developing it more and more. The only solution I have is to write down my ideas, save my code somewhere safe, then come back to it as soon as possible.

This year I made it a priority to get those notes out of my drafts folder, polish them up, and get them out there into the world. The result was a remarkable collection of tutorials that have really helped take the site to the next level:

  • I started the year with Xcode in 20 Seconds, which made 40 daily videos teaching interesting features of Xcode in 20 seconds or less. The...
]]>
Save 50% in the Hacking with Swift Black Friday sale https://www.hackingwithswift.com/articles/208/save-50-in-the-hacking-with-swift-black-friday-sale https://www.hackingwithswift.com/articles/208/save-50-in-the-hacking-with-swift-black-friday-sale All books and bundles are half price! Mon, 25 Nov 2019 10:54:49 +0000 If you want to take your Swift learning further without breaking the bank, you’ll be pleased to know that all Hacking with Swift books and bundles are half price for Black Friday 2019 – there has never been a better time to stock up on fantastic Swift tutorials!

New this year: The sale includes my latest bundle, the Swift Plus Pack, and you can even save 50% on the pre-order for my latest book: Swift on Sundays Volume One.

50% off all bundles

I try to keep the prices of my books as low as possible, but if you buy the bundle you get an extra saving – and if you buy a bundle during this Black Friday sale you get a triple saving!

50% off all books

All my books are half price for this sale, and still come with a lifetime Swift update policy that ensure your learning never goes out of date.

]]>
Nominations open for the 2019 Swift Community Awards https://www.hackingwithswift.com/articles/207/nominations-open-for-the-2019-swift-community-awards https://www.hackingwithswift.com/articles/207/nominations-open-for-the-2019-swift-community-awards Nominate the people and projects that help you the most Tue, 19 Nov 2019 22:19:16 +0000 The Swift Community Awards are back for their third year, helping celebrate our amazing community and recognize the hard work of people and projects that help make Swift great.

Right now you can post nominations across 10 categories:

  • Best newsletter
  • Best conference
  • Best podcast
  • Best design tool
  • Best third-party service
  • Best developer tool
  • Best open-source project
  • Most inspiring indie app
  • Most inspiring presentation
  • Rising star

All categories are optional, so you can vote only in the ones you want to.

Click here to find out more about the categories and add your nominations. Nominations close on November 26th, with the shortlist open for final voting on November 28th.

]]>
The Best Swift and iOS conferences in 2020 https://www.hackingwithswift.com/articles/206/the-best-swift-and-ios-conferences-in-2020 https://www.hackingwithswift.com/articles/206/the-best-swift-and-ios-conferences-in-2020 Learn more Swift and meet new friends at the same time. Wed, 13 Nov 2019 14:39:45 +0000 Our community has a huge number of awesome conferences around the world, so regardless of where you live there's usually a conference nearby. Of course, there are also many conferences far away too, so if you want to combine learning Swift with some sightseeing it's a double win!

I've had the privilege of attending so many events around the world, so each year I draw up a list of conferences I can personally vouch for – events where I know folks are welcomed regardless of their background, where you can expect high-quality speakers, and where there are lots of good opportunities for networking and making friends.

Below is my list for 2020, and I have included dates below where they have been announced. Where 2020 editions haven’t been announced yet, I’ve included last year’s month with a question mark.

iOS Conf SG

January 15th-18th, Singapore (Link)

This event always starts our year off with a bang, and is the largest iOS conference in south-east Asia. This year it now runs across two workshop days plus two days of sessions, and the speaker line-up already includes Dave Verwer, Ellen Shapiro, Meng To, and more. Last year I was really impressed by the huge range of attendees – many were from Singapore and Malaysia, of course, but also from Indonesia, Japan, Australia, and beyond; it's a massive mix.

dotSwift

February 3rd, Paris, France (Link)

dotSwift has a long-standing tradition of events in astonishing venues, tight time slots for speakers, and a complete ban on electronics in the audience. The result is something quite remarkable: given just 18 minutes to speak everyone on stage has honed their talk to the best it can be, so rather than chatting on Slack the audience is fully focused on learning. It sounds odd at first, but trust me: it works.

MobOS

February 20th-21st, Cluj Napoca, Romania (Link)

Returning for the seventh year in a row, MobOS is the largest and...

]]>
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 created a wide range of SwiftUI tutorials myself, but I’ve also been reading tutorials from many other developers. In this article I’ve brought 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 online – 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-started-wit...

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

]]>