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 New book: Understanding Swift https://www.hackingwithswift.com/articles/219/new-book-understanding-swift https://www.hackingwithswift.com/articles/219/new-book-understanding-swift Answers common beginner questions and more Fri, 29 May 2020 09:03:27 +0000 I've just published a new book called Understanding Swift, complementing my 100 Days of Swift and 100 Days of SwiftUI courses by answering the most common questions folks have. Everything I have released for the last 20 months has been available free, and this new book is also free right here: Understanding Swift

This book is different from my others that show you how to build stuff with Swift, because this one is trying to answer many of the "why" questions learners have – why are tuples different from structs? Why do copies of a class share data? Why would you want a failable initializer?

You might look at some of the questions and think they are easy, but every one of them was drawn from questions I've been asked by folks completing the 100 Days of Swift/SwiftUI – this book tries to bring them into one place so folks hit fewer problems and feel more encouraged.

If you'd prefer a download edition of Understanding Swift, you can buy it here. But I want to get this to everyone who needs it, so I'm retroactively adding it to my Swift Power Pack

Last December I launched a Patreon so folks could help support my work, and it's helped keep things afloat. So, Understanding Swift is dedicated to everyone who supports me on Patreon – thanks, folks!

You can find out more about my Patreon here.

PS: If you're following the 100 Days of Swift/SwiftUI, I have added links to Understanding Swift directly to each day so you have optional extra reading if you want it.

]]>
What’s new in Swift 5.3? https://www.hackingwithswift.com/articles/218/whats-new-in-swift-5-3 https://www.hackingwithswift.com/articles/218/whats-new-in-swift-5-3 Multiple trailing closures, massive package manager improvements, and more. Fri, 15 May 2020 13:10:35 +0000 Swift 5.3 brings with it another raft of improvements for Swift, including some powerful new features such as multi-pattern catch clauses and multiple trailing closures, plus some important changes for Swift Package Manager.

In this article I’m going to walk through each of the major changes, while providing hands-on code samples so you can try them yourself. I encourage you to follow the links through to the Swift Evolution proposals for more information, and if you missed my earlier what's new in Swift 5.2 article then check that out too.

Multi-pattern catch clauses

SE-0276 introduced the ability to catch multiple error cases inside a single catch block, which allows us to remove some duplication in our error handling.

For example, we might have some code that defines two enum cases for an error:

enum TemperatureError: Error {
    case tooCold, tooHot
}

When reading the temperature of something, we can either throw one of those errors, or send back “OK”:

func getReactorTemperature() -> Int {
    90
}

func checkReactorOperational() throws -> String {
    let temp = getReactorTemperature()

    if temp < 10 {
        throw TemperatureError.tooCold
    } else if temp > 90 {
        throw TemperatureError.tooHot
    } else {
        return "OK"
    }
}

When it comes to catching errors thrown there, SE-0276 lets us handle both tooHot and tooCold in the same way by separating them with a comma:

do {
    let result = try checkReactorOperational()
    print("Result: \(result)")
} catch TemperatureError.tooHot, TemperatureError.tooCold {
    print("Shut down the reactor!")
} catch {
    print("An unknown error occurred.")
}

You can handle as many error cases as you want, and you can even bind values from ...

]]>
The Complete Guide to Layout in SwiftUI https://www.hackingwithswift.com/articles/217/complete-guide-to-layout-in-swiftui https://www.hackingwithswift.com/articles/217/complete-guide-to-layout-in-swiftui HStack, VStack, ZStack, Spacer, GeometryReader, and more Fri, 01 May 2020 15:48:40 +0000 SwiftUI gives us a huge range of tools to control layouts, from the core tools of HStack, VStack, and ZStack, through to more advanced views such as GeometryReader and Group, plus modifiers such as layoutPriority().

I’ve published a lot of articles and videos about those and more, but this article brings them all together in one place for easy reference.

If I missed something off this list, let me know on Twitter.

How layout works in SwiftUI

Before we get into the details of specific layout techniques, you should start with my video “How layout works in SwiftUI” – it outlines exactly how things fit together to give us lots of power and flexibility:

If you’d rather read the article instead, you can find it here: How layout works in SwiftUI.

The basics of layout stacks, frames, and ForEach

A handful of view types lie at the center of all our SwiftUI layouts, and if you understand them then you’re already half way to making great UI.

Start with these four to get a firm understanding of the basics:

Of course, you’re not restricted to working in one dimension – you can create your own stacks if you want....

]]>
The Complete Guide to NavigationView in SwiftUI https://www.hackingwithswift.com/articles/216/complete-guide-to-navigationview-in-swiftui https://www.hackingwithswift.com/articles/216/complete-guide-to-navigationview-in-swiftui Programmatic navigation, customization, and more Wed, 29 Apr 2020 16:11:35 +0000 NavigationView is one of the most important components of a SwiftUI app, allowing us to push and pop screens with ease, presenting information in a clear, hierarchical way for users. In this article I want to demonstrate the full range of ways you can use NavigationView in your apps, including simple things like setting a title and adding buttons, but also programmatic navigation, creating split views, and even handling other Apple platforms such as macOS and watchOS.

 

 

Getting a basic NavigationView with a title

To get started with NavigationView you should wrap one around whatever you’re trying to display, like this:

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

For simpler layouts navigation views should be the top-level thing in your view, but if you’re using them inside a TabView then the navigation view should be inside the tab view.

When learning SwiftUI, one thing that folks find confusing is how we attach titles to a navigation view:

NavigationView {
    Text("Hello, World!")
        .navigationBarTitle("Navigation")
}

Notice how the navigationBarTitle() modifier belongs to the text view, not to the navigation view? That’s intentional, and is the correct way to add a title here.

You see, navigation views let us display new screens of content by sliding them in from the right edge. Each screen can have its own title, and it’s the job of SwiftUI to make sure that title is shown in the navigation view at all times – you’ll see the old title animate away, while the new title animates in.

Now think about this: if we had attached the title directly to the navigation view, w...

]]>
Spot the Swifty https://www.hackingwithswift.com/articles/215/spot-the-swifty https://www.hackingwithswift.com/articles/215/spot-the-swifty Explore a cartoon world without social distancing. Wed, 01 Apr 2020 08:00:04 +0000 It’s April Fools day, and with the world as it is right now I figured folks in our community could use a little distraction – even if only for 10 minutes.

So, I’ve spent the last six weeks working with the talented illustrator Gus Morais to produce a massive picture that’s packed with fun details for you to discover. Plus, there are 30 well-known folks from the Swift community scattered through the picture – can you find them all?

The original picture itself is huge, weighing in at 5374x3508, but once you factor in a key helping you identify everyone you should be looking for, the finished result is an eye-watering 12850x5700 pixels in size.

So, you should open one of the pictures below in a new window, then zoom to see all the details – along with the 30 people there’s lots more to discover! Some people are harder to discover than others, and honestly I think you’ll struggle to find all 30. Prove me wrong, if you dare!

Regardless, I hope this picture provides you with a little fun today. Thanks for being a part of our incredible community ❤️

Remember: these folks can stand close together because they are cartoons, but you’re not – stay safe, and practice social distancing!

I’ve provided two versions of the picture: the original, and the original plus a key. If you think you really know the Swift community then try the first one, but if you need a little help check out the second…

Spot the Swifty

Make sure and click the pictures to see the full-sized version!

Spot the Swifty with Key

]]>
8 essential apps for iOS developers https://www.hackingwithswift.com/articles/214/essential-apps-for-ios-developers https://www.hackingwithswift.com/articles/214/essential-apps-for-ios-developers Make iOS and macOS do more work for you Mon, 30 Mar 2020 15:07:21 +0000 App developers use apps just as much as anyone else, but as well as things like Overcast, PCalc, and Reddit, we also use apps specifically designed to make development easier – apps aimed at developers.

In this article I want to pick out a handful I can personally recommend. None of these were provided free; I bought them all and can recommend them all from experience. If you make a development-focused app that I missed off, send me a tweet with a link and I’ll check it out!

Adaptivity A

Apple gives us many sizes, colors, icons, and more to work with, and sometimes it can be hard to remember which is which – should you use readable content margins here, to layout margins? Which Dynamic Type font is the correct choice for a particular layout? How about when all those are used inside a local notification UI?

Adaptivity by Geoff Hackworth is an app that aims to answer all those questions and more, allowing you to see visually how various layout guides interact, how all the Dynamic Type font families look (even with custom font support), how the safe area adjusts as navigation views and toolbars are shown and hidden, and practically everything else you could want from your layouts.

The app itself is remarkably simple: you see various common layouts such as plain view controllers, table view controllers, split view controllers, and more, each overlaid with various colored lines showing you the available space using differing measurement guides. But the app then goes on to show you more complex scenarios: what happens if you show this view controller in a context menu, or as part of a local notification? It even has a home screen quick action showing you how the layout adapts inside an action extension!

It seems ridiculous that this app costs just $3.99, because if you use it just once to figure out a layout problem it has earned its money back immediately. Even better, it’s a universal purchase that works acr...

]]>
How to build neumorphic designs with SwiftUI https://www.hackingwithswift.com/articles/213/how-to-build-neumorphic-designs-with-swiftui https://www.hackingwithswift.com/articles/213/how-to-build-neumorphic-designs-with-swiftui Try out a new design trend and learn something new Wed, 26 Feb 2020 14:35:41 +0000 Neumorphic design is easily the most interesting design trend of recent months, although to be fair Apple did use it as their design motif way back in WWDC18. In this article we’re going to look at how you can build neumorphic designs using SwiftUI, why you might want to, and – most importantly – how we can modify those designs to be more accessible.

Important: Neumorphism – sometimes called neomorphism – has serious implications for accessibility, so although it’s tempting to read the first part of this article then skip the rest, I encourage you to stick around and learn the downsides as well as the upsides so you get the full picture.

 

 

The basics of neumorphism

Before we get into the code, I just want to briefly touch on the two core principles of this design trend, because it will be relevant as we progress:

  1. It uses highlights and shadows to define the shapes of objects on the screen.
  2. Contrast is generally reduced; full white or black aren’t used, which is what allows the highlights and shadows to stand out.

The end result is an “extruded plastic” look – a user interface design that certainly looks fresh and interesting without being harsh on your eyes. I can’t repeat enough that reducing contrast and relying on shadows for shapes has serious impacts on accessibility, and we’ll be coming back to this later.

However, I still think it’s worth taking the time to explore neumorphism in SwiftUI – even if you don’t use it in your own apps, it’s a bit like a coding kata that will help hone your skills.

OK, enough waffle – let’s look at some code.

Building a neumorphic card

The simplest starting point is to build a neumorphic card: a rounded rectangle that will contain some inf...

]]>
What’s new in Swift 5.2 https://www.hackingwithswift.com/articles/212/whats-new-in-swift-5-2 https://www.hackingwithswift.com/articles/212/whats-new-in-swift-5-2 Key path expressions as functions, callAsFunction, and more Wed, 05 Feb 2020 23:29:22 +0000 Swift 5.2 arrived with Xcode 11.4, and includes a handful of language changes alongside reductions in code size and memory usage, plus a new diagnostic architecture that will help you understand and resolve errors faster.

In this article I'm going to walk through what's changed with some hands-on examples so you can see for yourself how things have evolved. I encourage you to follow the links through to the Swift Evolution proposals for more information, and if you missed my earlier what's new in Swift 5.1 article then check that out too.

Key Path Expressions as Functions

SE-0249 introduced a marvelous shortcut that allows us to use keypaths in a handful of specific circumstances.

The Evolution proposal describes this as being able to use “\Root.value wherever functions of (Root) -> Value are allowed”, but what it means is that if previously you sent a Car into a method and got back its license plate, you can now use Car.licensePlate instead.

This is best understood as an example, so here’s a User type that defines four properties:

struct User {
    let name: String
    let age: Int
    let bestFriend: String?

    var canVote: Bool {
        age >= 18
    }
}

We could create some instance of that struct and put them into an array, like this:

let eric = User(name: "Eric Effiong", age: 18, bestFriend: "Otis Milburn")
let maeve = User(name: "Maeve Wiley", age: 19, bestFriend: nil)
let otis = User(name: "Otis Milburn", age: 17, bestFriend: "Eric Effiong")
let users = [eric, maeve, otis]

Now for the important part: if you want to get an array of all the users names, you can do so by using a key path like this:

let userNames = users....
]]>
Apple announces SwiftCrypto, an open-source implementation of CryptoKit https://www.hackingwithswift.com/articles/211/apple-announces-swiftcrypto-an-open-source-implementation-of-cryptokit https://www.hackingwithswift.com/articles/211/apple-announces-swiftcrypto-an-open-source-implementation-of-cryptokit Get Swifty cryptography everywhere Mon, 03 Feb 2020 17:35:39 +0000 Update: Cory Benfield from Apple has confirmed that on Apple's platforms SwiftCrypto is limited to those that support CryptoKit, and can't act as a polyfill for older releases such as iOS 11/iOS 12 and macOS 10.14. However, there's hope that might change – Cory added "we’d be happy to discuss that use-case with the community." In theory that could mean we get SwiftCrypto support for iOS 12 and earlier, which would be awesome!

Apple today released SwiftCrypto, an open-source implementation of the CryptoKit framework that shipped in iOS 13 and macOS Catalina, allowing us to use the same APIs for encryption and hashing on Linux.

The release of SwiftCrypto is a big step forward for server-side Swift, because although we’ve had open-source Swift cryptography libraries in the past this is the first one officially supported by Apple. Even better, Apple states that the “vast majority of the SwiftCrypto code is intended to remain in lockstep with the current version of Apple CryptoKit,” which means it’s easy for developers to share code between Apple’s own platforms and Linux.

What’s particularly awesome about SwiftCrypto is that if you use it on Apple platforms it effectively becomes transparent – it just passes your calls directly on to CryptoKit. This means you can write your code once using import Crypto, then share it everywhere. As Apple describes it, this means SwiftCrypto “delegates all work to the core implementation of CryptoKit, as though SwiftCrypto was not even there.”

The only exception here is that SwiftCrypto doesn’t provide support for using Apple’s Secure Enclave hardware, which is incorporated into devices such as iPhones, Apple Watch, and modern Macs. As the Secure Enclave is only available on Apple hardware, this omission is unlikely to prove problematic.

Try it yourself

SwiftCrypto is available today, so why not give it a t...

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

]]>