Swift fundamentals

What is defer in Swift?

Published on: April 29, 2024

Sometimes, we write code that needs set some state or perform some work at the start of a function and at the end of that same function we might have to reset that state, or perform some cleanup regardless of why we’re exiting that function. For example, you might have a function that creates a new Core Data object and depending on whether you’re able to enrich the object with data from the network you want to exit the function early. Regardless of how and why you exit the function, you want to save your newly created object. Writing our...

Read more...

Deciding between a computed property and a function in Swift

Published on: April 26, 2024

In Swift, we can use computed properties to derive a value from other values defined on the same object. Being able to do this is super convenient because it means that we don’t have to manually make sure that we update derived properties every time one of the “source” values changed. We’ll just recompute the property every time it’s accessed! This is very similar to having a function that takes no arguments and returns a value: struct User { let givenName: String let familyName: String // Should we use this? var fullName: String { return "\(givenName) \(familyName)" } // Or...

Read more...

if case let in Swift explained

Published on: April 26, 2024

In Swift, we can use the case keyword in multiple places. Most commonly, a case is used in switched but since you’re here, you might have seen a case in combination with an if statement. In this post, we’ll explore different places where we can use the case keyword to perform something called pattern matching in Swift. Pattern matching is a powerful feature of Swift that allows us to perform highly elegant checks to see if a given type matches a certain value. In this post, we’ll explore a specific kind of pattern matching in Swift; the if case let...

Read more...

What are lazy vars in Swift?

Published on: April 23, 2024

Sometimes when you’re programming you have some properties that are pretty expensive to compute so you want to make sure that you don’t perform any work that you don’t absolutely must perform. For example, you might have the following two criteria for your property: The property should be computed once The property should be computed only when I need it If these two criteria sound like what you’re looking for, then lazy vars are for you. A lazy variable is defined as follows: class ExamResultsAnalyser { let allResults: [ExamResult] lazy var averageGrade: Float = { return allResults.reduce(0.0, { total, result...

Read more...

Deciding between a for loop or forEach in swift

Published on: April 23, 2024

Swift offers multiple ways to iterate over a collection of items. In this post we’ll compare a normal for loop to calling forEach on a collection. Both for x in collection and collection.forEach { x in } allow you to iterate over elements in a collection called collection. But what are their differences? Does one outperform the other? Is one better than the other? We’ll find out in this post. Using a regular for loop I’ve written about for loops in Swift before so if you want an in-depth look, take a look at this post. A regular for loop...

Read more...

An extensive guide to sorting Arrays in Swift

Published on: April 7, 2021

When you're working with Arrays in Swift, it's likely that you'll want to sort them at some point. In Swift, there are two ways to sort an Array: Through the Comparable implementation for each element in your array By providing a closure to perform a manual/specialized comparison between elements If you have a homogenous array of elements, for example [String], you can rely on String's implementation of Comparable to sort an array of String in some sensible manner. There are two ways to sort an array of Comparable elements: var strings = ["Oh", "Hello", "World", "This", "Is", "An", "Unsorted", "Array"]...

Read more...

Using Closures to initialize properties in Swift

Published on: April 8, 2020

There are several ways to initialize and configure properties in Swift. In this week's Quick Tip, I would like to briefly highlight the possibility of using closures to initialize complex properties in your structs and classes. You will learn how you can use this approach of initializing properties, and when it's useful. Let's dive in with an example right away: struct PicturesApi { private let dataPublisher: URLSession.DataTaskPublisher = { let url = URL(string: "https://mywebsite.com/pictures")! return URLSession.shared.dataTaskPublisher(for: url) }() } In this example, I create a URLSession.DataTaskPublisher object using a closure that is executed immediately when PicturesApi is instantiated. Even though...

Read more...

Removing duplicate values from an array in Swift

Published on: March 18, 2020

Arrays in Swift can hold on to all kinds of data. A common desire developers have when they use arrays, is to remove duplicate values from their arrays. Doing this is, unfortunately, not trivial. Objects that you store in an array are not guaranteed to be comparable. This means that it's not always possible to determine whether two objects are the same. For example, the following model is not comparable: struct Point { let x: Int let y: Int } However, a keen eye might notice that two instances of Point could easily be compared and two points that are...

Read more...

What are computed properties in Swift and when should you use them?

Published on: March 9, 2020

One of Swift's incredibly useful features is its ability to dynamically compute the value of a property through a computed property. While this is a super handy feature, it can also be a source of confusion for newcomers to the language. A computed property can look a bit strange if you haven't seen one before; especially when you are learning about custom get and set closures for properties at the same time. In this week's post, I would like to take some time to explain computed properties in-depth so you can begin using them in your codebase with confidence. By...

Read more...

How to sort an Array based on a property of an element in Swift?

Published on: January 20, 2020

This post is a short demo of using Swift's sort() and sort(by:) methods. For a more comprehensive overview of sorting, and some background information on how Swift's sorting works I recommend you take a look at this updated post The easiest way to sort an Array in Swift is to use the sort method. This method is available for all Arrays that have Comparable elements and it sorts your array in place: var words = ["hello", "world", "this", "is", "a", "list", "of", "strings"] words.sort() // words is now ["a", "hello", "is", "list", "of", "strings", "this", "world"] This modifies the input...

Read more...