UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

That page doesn't exist, but based on searching the site here are some pages that might be what you're looking for…

How to set local alerts using UNNotificationCenter

Example Code Local notifications are messages that appear on the user's lock screen when your app isn't running. The user can then swipe to unlock their device and go straight to your app, at which point you can act on the notification. All this is done using the User Notifications framework, so import that now: import UserNotification... Read more >>

How to show multiple alerts in a single view

Example Code ...ckier if you try to show two or more alerts from a single view – you might find that one alert works and the other doesn’t, for example. To solve this, you need to make sure you attach no more than one alert() modifier to each view. That might sound limiting, but remember: you don’t need to attach the alerts to the same view... Read more >>

How to create and use task local values

Example Code Swift lets us attach metadata to a task using task-local values, which are small pieces of information that any code inside a task can read. For example, you’ve already seen how we can read Task.isCancelled to see whether the current task is cancelled or not, but that’s not a true static property – it’s scoped to the current task, rath... Read more >>

NSAttributedString by example

Article ...nt to use them with UILabel and UITextView, both of which accept attributed strings directly. In this article I'll walk you through examples of what NSAttributedString is capable of: creating strings by hand, adding and enumerating attributes, adding links and images, and more. All these code samples are written to work with a Swi... Read more >>

UIActivityViewController by example

Article ...ge, and more, and is also able to add our app’s own services alongside the others. In this article I'll walk through some complete examples of using UIActivityViewController, partly so you can see what it’s capable of, and partly also so you have one reference guide to refer back to in the future. Sharing basic content Let’s ... Read more >>

Scheduling local notifications

Project iOS has a framework called UserNotifications that does pretty much exactly what you expect: lets us create notifications to the user that can be shown on the lock screen. We have two types of notifications to work with, and they differ depending on where they were created: local notifications are ones we schedule locall... Read more >>

SwiftUI by Example: Now updated for iOS 16

Article This week I published the biggest ever update to SwiftUI by Example, adding lots of new sample code plus 100 new Xcode projects to download. The initial goal was to update the book for iOS 16, but I ended up going back and adding coverage of functionality intr... Read more >>

Learn SwiftUI with SwiftUI By Example

Article 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 solu... Read more >>

How to render example content using prepareForInterfaceBuilder()

Example Code Whenever you create a custom UIView subclass using @IBDesignable, it’s usually a good idea to provide it with some sample content so it can render meaningfully at design time. For example, here’s a simple ShapeView class that renders a UIBezierPath inside a view, using CAShapeLayer: @IBDesignable class ShapeView: UIView { @IBInspectable var strokeColor: UIColor = UIColor.... Read more >>

UIStackView by example

Project ...StackView gives us: a flexible, Auto Layout-powered view container that makes it even easier to build complex user interfaces. As an example, lets say you want users to fill in a short form: you have a label saying "Name" then a UITextField to the right of it; beneath that you have another label saying "Address" and a UITextView be... Read more >>

Property wrappers are now supported for local variables

Article ...es in an easy, reusable way, but in Swift 5.4 their behavior got extended to support using them as local variables in functions. For example, we could create a property wrapper that ensures its value never goes below zero: @propertyWrapper struct NonNegative { var value: T var wrappedValue: T { get { value } ... Read more >>

Local functions now support overloading

Article ...n practice means nested functions can now be overloaded so that Swift chooses which one to run based on the types that are used. For example, if we wanted to make some simple cookies we might write code like this: struct Butter { } struct Flour { } struct Sugar { } func makeCookies() { func add(item: Butter) { print("A... Read more >>

lazy now works in local contexts

Article The lazy keyword has always allowed us to write stored properties that are only calculated when first used, but from Swift 5.5 onwards we can use lazy locally inside a function to create values that work similarly. This code demonstrates l... Read more >>

How to use local variable observers

Example Code You should already be familiar with the concept of property observers in Swift – those willSet and didSet blocks you can attach to property on classes and structs. Well, those same blocks can be attached to local and global variables as well, allowing you to respond to changes easily. The syntax is identical: create your varia... Read more >>

Expanding the Swift Knowledge Base

Article I've just added 270 articles to my Swift Knowledge Base, taking it up to 576 tips, techniques, and answers for Swift developers – all updated for the latest version of Xcode and Swift. Click here to browse the knowledge base b... Read more >>

How to count objects in a set using NSCountedSet

Example Code One of my favorite little gems in Cocoa Touch is called NSCountedSet, and it's the most efficient way to count objects in a set. Here's the code: let set = NSCountedSet() set.add("Bob") set.add("Charlotte") set.add("John") set.add("Bob") se... Read more >>

When to use a set rather than an array

Example Code Sets and arrays both store objects of your choosing, but they have four important differences: Sets do not store objects in the order they add them. Instead, they are stored in a way to make them fast to find, which means... Read more >>

How to set the background color of list rows using listRowBackground()

Example Code ...alled listRowBackground(). This accepts any kind of view – including colors, images, and shapes – and uses it behind rows. For example, this creates a list using 10 rows, each with a red background color: List { ForEach(0.. Read more >>

How to set a custom title view in a UINavigationBar

Example Code ...omizes the navigation bar if it is viewed inside a navigation controller. This is where you add left and right bar button items, for example, but also where you can set a title view: any UIView subclass that is used in place of the title text in the navigation bar. For example, if you wanted to show an image of your logo rather tha... Read more >>

How to set the clock in the iOS Simulator

Example Code By default the iOS Simulator shows whatever the time is on your Mac, but you can use Xcode’s simctl command to override that with a custom time. For example, Apple always uses 9:41am in their screenshots, because that was the time the original iPhone was announced. If you want to get the same thing in your simulator screenshots, use this command: ... Read more >>

A new Set data structure

Article ...ept with value semantics. Sets work similarly to arrays except they are not ordered and do not store any element more than once. For example: var starships = Set() starships.insert("Serenity") starships.insert("Enterprise") starships.insert("Executor") starships.insert("Serenity") starships.insert("Serenity") Even though that code ... Read more >>

How to set baselines for your performance tests

Example Code All performance tests in Xcode can have baselines attached to them, which are stored results that you consider representative of your app’s performance as things stand. The baseline is useful because it gives Xcode a measuring point for all other changes yo... Read more >>

When should you use an array, a set, or a tuple in Swift?

Article Because arrays, sets, and tuples work in slightly different ways, it’s important to make sure you choose the right one so your data is stored correctly and efficiently. Remember: arrays keep the order and can have duplicates, sets are unordered and can’t have duplicates, and tup... Read more >>

How to set the tint color of a UIView

Example Code The tintColor property of any UIView subclass lets you change the coloring effect applied to it. The exact effect depends on what control you're changing: for navigation bars and tab bars this means the text and icons on their buttons, for text views it means the selection cursor and highl... Read more >>

How to set the tabs in a UITabBarController

Example Code If you're creating your tab bar controller from scratch, or if you just want to change the set up of your tabs at runtime, you can do so just by setting the viewControllers property of your tab bar controller. This expects to be given an array of view controllers in the order ... Read more >>

How set different widths for a UISegmentedControl's elements

Example Code Segmented controls give each segment equal width by default, which is aesthetically pleasing when you have space to spare but technically irritating when space is tight. Rather than try to squash too much into a small space, you have two options: set custom segment widths, or ask iOS to size them individually fo... Read more >>

How to set prompt text in a navigation bar

Example Code You should already know that you can give a title to a navigation controller's bar by setting the title property of your view controllers or a view controller's navigationItem, but did you also know that you can provide prompt text too? When provided... Read more >>

What's new in Swift 5.5?

Article ...mmonly 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 ser... Read more >>

What’s new in Swift 5.7

Article ...cy clean ups around the any and some keywords. In this article I want to introduce you to the major changes, providing some hands-on examples along the way so you can see for yourself what’s changing. Many of these changes are complex, and many of them are also interlinked. I’ve done my best to break things down into a sensible... Read more >>

How to test your user interface using Xcode

Article ...he process work. The project we’ll be using is a simple sandbox with a variety of controls – you can download it here. Give the example app a try now – it’s a simple sandbox app with a small amount of functionality: If you enter text into the text box you’ll see the same text appear in the label below. Dragging the sli... Read more >>

Learn essential Swift in one hour

Article ...(), like this: print(colors.contains("Octarine")) Dictionaries Dictionaries store multiple values according to a key we specify. For example, we could create a dictionary to store information about a person: let employee = [ "name": "Taylor", "job": "Singer" ] To read data from the dictionary, use the same keys you used whe... Read more >>

The Ultimate Guide to WKWebView

Article ...file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read. For example, if you wanted to load a file called "help.html" you might use code like this: if let url = Bundle.main.url(forResource: "help", withExtension: "html") { webView.loadFileURL(url, allowingR... Read more >>

SwiftUI tips and tricks

Example Code ...e text fields and sliders, you can use a constant binding instead. This will allow you to use the object with a realistic value. For example, this creates a text field with the constant string “Hello”: TextField("Example placeholder", text: .constant("Hello")) .textFieldStyle(.roundedBorder) Important: If you’re using Xco... Read more >>

Swiftoberfest 2019

Article ... 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 ... Read more >>

What’s new in Swift 5.0

Article ... type, checking for integer multiples and more. Try it yourself: I created an Xcode Playground showing what's new in Swift 5.0 with examples you can edit. A standard Result type Watch the video SE-0235 introduces a Result type into the standard library, giving us a simpler, clearer way of handling errors in complex code su... Read more >>

What’s new in iOS 12?

Article ...improvements to Xcode, but I'll be covering it all here. In this article I'll walk you through the major changes, complete with code examples, so you can try it for yourself. Note: you will need macOS Mojave if you want to use the new Create ML tools. You might also want to read what’s new in Swift 4.2. I also published API diff... Read more >>

The Complete Guide to Optionals in Swift

Article ...d to topics that will interest more experienced developers. What are optionals? Optionals represent something that has no value. For example, consider this code: let names = ["Margaret", "Matthew", "Megan"] let position = names.index(of: "Mxyzptlk") That creates an array of names and looks up the position of a name that doesn’t e... Read more >>

Xcode UI Testing Cheat Sheet

Article ...??s usually a good idea to allow a little leeway because you’re working with a real device – animations might be happening, for example. So, instead of using exists it’s common to use waitForExistence(timeout:) instead, like this: XCTAssertTrue(app.alerts["Warning"].waitForExistence(timeout: 1)) If that element exists immedi... Read more >>

8 Common SwiftUI Mistakes - and how to fix them

Article ... 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 ... Read more >>

What’s new in Vapor 3?

Article ...ches for developers. A non-blocking architecture means that any operation that takes more than a tiny amount of time to run – for example a network request, a database request, or even rendering templates – is now run asynchronously. That is, your network request code returns immediately even though the work itself has not co... Read more >>

What’s new in Swift 5.9?

Article ...king yet another mammoth release. In this article I’ll walk you through the most important changes in this release, providing code examples and explanations so you can try it all yourself. You’ll need the latest Swift 5.9 toolchain installed in Xcode 14, or the Xcode 15 beta. if and switch expressions SE-0380 adds the ability f... Read more >>

What’s new in Swift 5.4?

Article ...tatic 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!") ... Read more >>

Vapor + Leaf templating cheat sheet

Article ...or new LeafTest --template=twostraws/vapor-clean cd LeafTest That creates a new Vapor project called LeafTest, asking it to clone my example project from GitHub. Don’t worry: that example project contains the absolute least amount of code required to set up a Vapor server. Adding Leaf to your project Adding Leaf takes two steps. ... Read more >>

The Complete Guide to SF Symbols

Article ...ctivate these by name – e.g. “bell.slash” – but in SwiftUI there’s a symbolVariant() modifier that makes this easier. For example, this renders a bell icon with a slash through it: Image(systemName: "bell") .symbolVariant(.slash) And this surrounds the bell with a square: Image(systemName: "bell") .symbolVariant(... Read more >>

Using alert() and sheet() with optionals

Project SwiftUI has two ways of creating alerts and sheets, and so far we’ve mostly only used one: a binding to a Boolean that shows the alert or sheet when the Boolean becomes true. The second option allows us to bind an optional to the alert or sheet, and we used it briefly when presenting map pins. If you... Read more >>

Build your first app with SwiftUI and SwiftData

Article ...s. When we're using a local property with @State or similar, SwiftUI automatically creates three ways of accessing the property. For example, if we had an integer called age, then: If we read age directly, we can get or set the integer. If we use $age, we access a binding to the data, which is a two-way connection to the data that... Read more >>

Super-powered string interpolation in Swift 5.0

Article ...erpolation handles parameters. You see, appendInterpolation() so that we can handle various different data types in unique ways. For example, we could write some code to handle Twitter handles, looking specifically for the twitter parameter name like this: mutating func appendInterpolation(twitter: String) { appendLiteral("@\(t... Read more >>

Why many developers prefer Swift to Objective-C

Article ...ill encounter in the work setting and in useful Stack Overflow answers. Objective-C's positive influence on Swift is evident in, for example, named parameters, reference counting, and single inheritance. Joachim Bondo: It’s frightening how quickly you loose the touch! I never had problems with the square brackets, but it’s sudd... Read more >>

How to Become an iOS Developer in 2021

Article ... you’re learning. SwiftUI was built for Swift, using language features to help you avoid problems and get maximum performance. For example, if you change some data on one screen of an app, SwiftUI will automatically make sure that new data is updated anywhere else in your app that uses it – you don’t need to write code to ke... Read more >>

How to save and share your work with GitHub

Article ...you have there, but if you don’t you can get my original implementation from GitHub (ironic, huh?), by clicking here. Warning: The example project has been written specifically for this tutorial series, and contains mistakes and problems that we’ll be examining over this tutorial series. If you’re looking for example code to ... Read more >>

10 Quick Swift Tips

Article ...to take advantage of if you know they exist. In this article I want to walk you through ten of them quickly, including hands-on code examples so you can try them immediately. 1. Existentials of classes and protocols An “existential type” allows us to say what kind of functionality we want a type to have rather than requesting s... Read more >>

Get started with Vapor 3 for free

Article ...er/install)" Note: installing Homebrew will ask for your password. Now we can go ahead and create a new project for Vapor 3. In this example we’re going to build a simple web chat called WaffleSpot: users can enter a username and a message into a web form, which we’ll then save to an SQLite database. They’ll also be able to r... Read more >>

The complete guide to routing with Vapor 3

Article ...application, so it won’t surprise you to learn it can do a lot depending on your needs. In this article we’re going to set up an example web project using Vapor, then experiment with various ways of handling routes. We’re going to start off with the basics for folks who haven’t tried Vapor before, but quickly ramp up to mor... Read more >>

Build a unit converter for watchOS

Article ... important. So, this property needs to store the human-readable name of the conversions – “Distance” or “Temperature”, for example – along with an array of the various measurements inside each conversion group, all of which descend from the Dimension class. You might think that could be represented using a dictionary li... Read more >>

What’s new in Swift 4.2

Article ...ings, count(where:), isMultiple(of:), and more. Try it yourself: I created an Xcode Playground showing what's new in Swift 4.2 with examples you can edit. Derived collections of enum cases SE-0194 introduces a new CaseIterable protocol that automatically generates an array property of all cases in an enum. Prior to Swift 4.2 thi... Read more >>

5 Steps to Better SwiftUI Views

Article ...ough 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 wh... Read more >>

Countdown to WWDC 18

Article ...Twitter. WWDC-60: How to use the coordinator pattern in iOS apps WWDC-59: Server-side Swift: Kitura vs Vapor WWDC-58: How to render example content using prepareForInterfaceBuilder() WWDC-57: Understanding protocol associated types and their constraints WWDC-56: Controlling extension points in protocols WWDC-55: How to loop over a... Read more >>

The Complete Guide to NavigationView in SwiftUI

Article ... could be a custom view of your choosing, but it also could be one of SwiftUI’s primitive views if you’re just prototyping. For example, this pushes directly to a text view: NavigationView { NavigationLink(destination: Text("Second View")) { Text("Hello, World!") } .navigationTitle("Navigation") } Because I... Read more >>

How to build your first SwiftUI app with Swift Playgrounds

Article ...lots of these built right in to SwiftUI, and you’ll often find yourself using several at once to get exactly the right effect. For example, try changing your text to include these modifiers below: Text("Hello, world!") .font(.largeTitle) .foregroundColor(.blue) That will give the text a large font and a blue color. Yo... Read more >>

What’s new in Swift 5.6?

Article ...e refining others as we get closer to Swift 6. In this article I want to introduce you to the major changes, providing some hands-on examples along the way so you can see for yourself what’s changing. Tip: You can also download this as an Xcode playground if you want to try the code samples yourself. Introduce existential any ... Read more >>

Showing and hiding views

Project ...when those conditions become true or false the sheet will either be presented or dismissed respectively. Let’s start with a simple example, which will be showing one view from another using a sheet. First, we create the view we want to show inside a sheet, like this: struct SecondView: View { var body: some View { Tex... Read more >>

How to use regular expressions in Swift

Article ...rom this one: Advanced regular expression matching with NSRegularExpression.  First, the basics Let’s start with a couple of easy examples for folks who haven’t used regular expressions before. Regular expressions – regexes for short – are designed to let us perform fuzzy searches inside strings. For example, we know tha... Read more >>

How to create multi-column lists using Table

Example Code ... On iPhone tables are collapsed down to show just the first column of data, but on iPad and Mac they will show all their data. As an example, we might have a simple User struct like this one: struct User: Identifiable { let id: Int var name: String var score: Int } I’ve used both a String and Int for types there, bec... Read more >>

The Auto Layout cheat sheet

Article ...straints, and they also happen to have a really natural form too. In the code below I’ve used childView and parentView as names of example views, where the child is placed inside the parent. Pin a child view to edges of its parent This will make the child view run to the very edges of its parent: NSLayoutConstraint.activate([ ... Read more >>

What you learned

Guide You’ve made your first two projects now, and completed a technique project too – this same cadence of app, game, technique is used all the way up to project 30, and you’ll start to settle into it as time goes by. Both the app and the game were built with UIKit – someth... Read more >>

How to find and fix slow drawing using Instruments

Article ...comes with a range of tools to help us identify and resolve drawing issues, and I want to walk you through some of them using a real example. This is a topic I talk about a lot – see here for example – because it really matters, and every time I speak or write about it some folks learn it for the first time. First, you need to... Read more >>

How to create and use protocols

Tutorial ...ey don’t actually put any code behind it – they just say that the properties and methods must exist, a bit like a blueprint. For example, we could define a new Vehicle protocol like this: protocol Vehicle { func estimateTime(for distance: Int) -> Int func travel(distance: Int) } Let’s break that down: To create a new... Read more >>

Learn SwiftUI with free tutorials

Article ... 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 ... Read more >>

Server-Side Swift: Kitura vs Vapor

Article ...e template is available for Vapor 3. Annoyingly, it’s more of a sample app than an actual template, so you’ll need to delete its example Todo List code before you can actually use it. Worse, it groups your source code into “Models” and “Controllers”, which is the kind of thing you do before you realize how terrible such... Read more >>

Creative borders and fills using ImagePaint

Project SwiftUI relies heavily on protocols, which can be a bit confusing when working with drawing. For example, we can use Color as a view, but it also conforms to ShapeStyle – a different protocol used for fills, strokes, and borders. In practice, this means we can modify the default text view so t... Read more >>

Checklist: How to make your iOS app more accessible

Article ... hints should start with a third-person singular verb that completes the sentence “this button…” or “this control…”. For example “Adds a song to your playlist.” Ending with a full stop or period helps VoiceOver read the hint more naturally. If you localize your app, make sure you localize your accessibility labels a... Read more >>

How to document your project with DocC

Article ...ome specific things that both Xcode and DocC look for, and if you add those it will really enrich the documentation you provide. For example, the Returns keyword lets you specify what value the caller can expect back when the function runs successfully. This isn’t just the data type – Xcode can figure that out for itself – b... Read more >>

What’s new in Swift 4.1

Article ... take a look at the top new features for this release… Update: I created an Xcode Playground showing what's new in Swift 4.1 with examples you can edit. Synthesized Equatable and Hashable The Equatable protocol allows Swift to compare one instance of a type against another. When we say 5 == 5, Swift understands what that means ... Read more >>

How to use inner shadows to simulate depth with SwiftUI and Core Motion

Article ...: ObservableObject { private let motionManager = CMMotionManager() @Published var x = 0.0 @Published var y = 0.0 } In my example code, we want to start reading motion data as soon as this manager is started, so we’ll use the initializer to call startDeviceMotionUpdates() on our motion manager. This needs to know where... Read more >>

What's new in Swift 5.8

Article ...squeezed into Swift 5.7! In this article I’m going to walk you through the most important changes this time around, providing code examples and explanations so you can try it all yourself. You’ll need Xcode 14.3 or later to use this, although some changes require a specific compiler flag before Swift 6 finally happens. Tip: Yo... Read more >>

How to use Result in Swift

Article ... we could write a function that connects to a remote server to figure out how many unread messages are waiting for the user. In this example code we’re going to have just one possible error, which is that the requested URL string isn’t valid: enum NetworkError: Error { case badURL } The fetching function will accept a URL s... Read more >>

What’s new in SwiftUI for iOS 14

Article SwiftUI was inevitably going to see big changes this year, and I’m really excited to experiment with them all – text views, color pickers, progress views, and even limited support for grids have all landed. Alongside massive... Read more >>

Resizing images to fit the available space

Project ...t, add some sort of image to your project. It doesn’t matter what it is, as long as it’s wider than the screen. I called mine “Example”, but obviously you should substitute your image name in the code below. Now let’s draw that image on the screen: struct ContentView: View { var body: some View { Image("Exampl... Read more >>

How to use the coordinator pattern in iOS apps

Article ... the six most common questions I get asked when folks move to coordinators. In this article I want to provide you with a hands-on example of the coordinator pattern, which takes responsibility for navigation out of your view controllers and into a separate class. This is a pattern I learned from Soroush Khanlou – folks who’... Read more >>

User interface testing with XCTest

Project ...arDown() methods again, although this time the setup() method actually has some code in to get things started. You'll also see a testExample() method, but please just delete that – we'll be writing our own. We're going to start with a very simple test: when the view controller loads, does it show the correct number of words? If ... Read more >>

How to deliver a talk at a programming conference

Article ...et started. In this article you’ll find: Tips for locating good events where you can speak How to write good proposals and titles Examples of speaker bios from well-known folks in our industry Advice for crafting great slides and delivering your talk At the same time, I’m also just one person with one very specific background... Read more >>

What’s new in Swift 5.1

Article ...tone we’re also getting a number of important language improvements, and in this article I’ll walk through them and provide code examples so you can see them in action. As you're reading through, chances are you'll see just how many of these features relate to SwiftUI, and in fact I think it's fair to say that SwiftUI would be ... Read more >>

How to find and fix slow code using Instruments

Article ...rofiler and system trace. You don’t need to have completed the two previous parts of this tutorial, but you do need to download my example Xcode project from GitHub. I should repeat the large and important warning… Warning: That project is specifically written to be bad – please don’t use it as a learning exercise, other t... Read more >>

How to use @MainActor to run code on the main queue

Example Code ...ain actor. This is particularly useful for any types that exist to update your user interface, such as ObservableObject classes. For example, we could create a observable object with two @Published properties, and because they will both update the UI we would mark the whole class with @MainActor to ensure these UI updates always ha... Read more >>

How to create a custom gauge control using UIKit

Article ...TickCount plus one. The “plus one” part is important, because we draw the ticks inside the segments rather than at the ages. For example, if we had a segment angle of 100 and wanted three ticks, dividing 100 by three would place ticks at 33, 66, and 99 – there would be a tick right next to the major tick line at 100. But if ... Read more >>

Why many developers still prefer Objective-C to Swift

Article ...xing of the C parts of Objective-C with the dynamic messaging parts. All that gets more difficult, so much that you couldn’t, for example, write CoreData in Swift. Also churn: I just tried to find some sample code for Apple Pencil. All of it was Swift. None of it compiles today. Have you ever felt developers might get a little s... Read more >>

How to use custom string interpolation

Article ...s behavior), or wanted to format that output so it could be user-facing, then you could use the new string interpolation system. For example, if we had a struct like this: struct User { var name: String var age: Int } If we wanted to add a special string interpolation for that so that we printed users neatly, we would add a... Read more >>

Understanding frames and coordinates inside GeometryReader

Project ...c usage, what GeometryReader does is let us read the size that was proposed by the parent, then use that to manipulate our view. For example, we could use GeometryReader to make a text view have 90% of all available width regardless of its content: struct ContentView: View { var body: some View { GeometryReader { geo in... Read more >>

Advanced coordinators in iOS

Article ...ou use protocols or closures instead? I'll be giving you lots of hands-on code along the way, because I want you to see real-world examples of how these problems are solved. If you missed my earlier tutorial on the coordinator pattern, you should start there: How to use the coordinator pattern in iOS apps. Prefer video? The scr... Read more >>

Showing multiple options with confirmationDialog()

Project SwiftUI gives us alert() for presenting important choices, and sheet() for presenting whole views on top of the current view, but it also gives us confirmationDialog(): an alternative to alert() that lets us add many buttons. Visually alerts and confirmation dialogs are very different: on iPhones, al... Read more >>

How to wrap a C library in Swift

Article ....1"), In my real SwiftGD project there are multiple source code files to handle different aspects of the project, but in this simple example it’s easiest just to write code directly into SwiftGD.swift. So, please open that file for editing now – something like Xcode is fine. Even though I’ve tried to strip it back to the bare... Read more >>

What’s new in iOS 13?

Article ...ive user interfaces in Swift for more information. If you'd like to learn SwiftUI, you should read either my online book SwiftUI By Example or follow my 100 Days of SwiftUI course, both of which are free. UIKit: Dark mode, macOS, and more At WWDC18 Apple announced a preview of a new technology designed to make it easy to port iOS... Read more >>

Swift 4.2 improves Hashable with a new Hasher struct

Article ...s one of Swift’s most important protocols, but it often goes unnoticed. You use it every time you create dictionaries or sets, for example, because those types create hashes of your data to figure out where it should be stored. Before Swift 4.1, conforming to Hashable was complex because you needed to calculate a hashValue proper... Read more >>

How to find and fix memory leaks using Instruments

Article ...you to the allocations instrument, which is designed to identify where and when memory is allocated. If you don’t already have the example project to hand, please download it and open it in Xcode. Now press Cmd+I to build and run the project for Instruments, select the allocations instrument, then press Choose. Just like with th... Read more >>

Write better code with Swift Algorithms

Article ...ants of chunking functions that do just that, and they turn complex, error-prone work into one-liners with extreme efficiency. As an example, we could create an array of students with names and grade letters like this: struct Student { let name: String let grade: String } let results = [ Student(name: "Taylor", grade: ... Read more >>

Capture lists in Swift: what’s the difference between weak, strong, and unowned references?

Article ...red values are always optional in Swift. This stops you assuming they are present when in fact they might not be. We can modify our example to use weak capturing and you’ll see an immediate difference: func sing() -> () -> Void { let taylor = Singer() let singing = { [weak taylor] in taylor?.playSong() r... Read more >>

What’s new in Swift 5.3?

Article ...ity 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 ... Read more >>

How to add advanced text styling using AttributedString

Example Code ...through, web links, background colors, and more. Sadly, it has a rather bafflingly opaque API so I want to show you a whole bunch of examples to help get you started. We can create an AttributedString with common properties such as font, background color, and foreground color: struct ContentView: View { var message: AttributedS... Read more >>

What’s new in Xcode 14?

Article ...for Xcode’s source editor – it just keeps getting smarter and smarter in ways that I hadn’t even imagined were possible. As an example, let’s say we had a Player struct such as this one: struct Player: Identifiable { var id = UUID() var name: String var score = 0 } Swift will automatically generate a memberwise ... Read more >>

Swift Playgrounds 4 is here, and it’s a thing of beauty

Article ... can also make the console permanently visible if you prefer. But, critically we don’t get some of Xcode’s biggest problems. For example, when you want to add a capability to a Swift Playgrounds app, it’s all done using a beautiful new user interface where you select from a list, then enter any addition data as prompted – t... Read more >>

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.