Swift fundamentals
An extensive guide to sorting Arrays in Swift
Published on: April 7, 2021When 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, 2020There 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, 2020Arrays 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, 2020One 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, 2020This 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...How to add an element to the start of an Array in Swift?
Published on: January 19, 2020You can use Array's insert(_:at:) method to insert a new element at the start, or any other arbitrary position of an Array: var array = ["world"] array.insert("hello", at: 0) // array is now ["hello", "world"] Make sure that the position that you pass to the at: argument isn't larger than the array's current last index plus one. For example: // this is fine var array = ["hello"] array.insert("world", at: 1) // this will crash var array = ["hello"] array.insert("world", at: 2) If you have any questions about this tip, or if you have feedback for me, don't hesitate to reach...
Read more...Removing a specific object from an Array in Swift
Published on: January 10, 2020Arrays in Swift are powerful and they come with many built-in capabilities. One of these capabilities is the ability to remove objects. If you want to remove a single, specific object from an Array and you know its index, you can use remove(at:) to delete that object: var array = [1, 2, 3] array.remove(at: 0) // array is now [2, 3] If you don't know the object's position in the Array and the Array's elements conform to Equatable, you can look up the first index of the object you're looking for with firstIndex(of:) and you can then proceed to delete...
Read more...How to filter an Array in Swift?
Published on: January 9, 2020When you have an Array of elements, and you want to drop all elements that don't match specific criteria from the Array, you're looking for Array's filter(isIncluded:) method. Let's say you have an array of words and you only want to keep the words that are longer than three characters: let words = ["hello", "world", "this", "is", "a", "list", "of", "strings"] let filtered = words.filter { word in return word.count >= 3 } // filtered is ["hello", "world", "this", "list", "strings"] The filter(isIncluded:) method takes a closure that is executed for every element in the source Array. If you return...
Read more...Swift’s typealias explained with five examples
Published on: January 2, 2020Swift grants developers the ability to shadow certain types with an alternative name using the typealias keyword. We can use this feature to create tuples and closures that look like types, or we can use them to provide alternative names for existing objects. In this post, we'll look at five ways in which typealiases can help you write cleaner and better code. 1. Improving readability with type aliases Perhaps this is the most obvious yet also somewhat underused way to use a typealias. When you have a type in your code that is very long or deeply nested, you could...
Read more...Reversing an Array in Swift
Published on: January 1, 2020You can reverse an Array, and any other Collection in Swift using the reverse method. For example var input = [1, 2, 3] print(input) // [1, 2, 3] input.reverse() print(input) // [3, 2, 1] The code above takes an array (input) and reverses it in-place using the reverse() method. This only works if your array is mutable. If you want to reverse an immutable array that's defined as let, or if you don't want to alter the original input you can use reversed() instead of reverse(): var input = [1, 2, 3] print(input) // [1, 2, 3] var reversed =...
Read more...