Tuesday, May 03

Swift tips

Whether you are new to Swift development or a seasoned iOS developer, you may find the following tips useful. I came across them during my learning journey and I thought it will be good to share them.

Use flatmap to remove nil values from an array

In Swift, flatmap has two purposes. The first one is to flatten an array:

let collectionOfLetters = [["a","b"],["d","e","f"]]
let letters = collectionOfLetters.flatMap { $0 }
Output: ["a","b","d","e","f"]

But, flatmap can also be used to remove nil values in a less verbose way:

let collectionOfLetters:[String?] = ["a",nil,"d","e",nil]
let letters = collectionOfLetters.flatMap { $0 }
Output: ["a","d","e"]

Use private setter but public getter

Instead of having the following code:

public class Book {
    private var _title: String
    public var title: String {
        return _title

You can do:

public class Book {
    public private(set) var title: String

This give us public getters but private setters, hooray!

Use defer to make your code cleaner

Defer comes in handy when you want a block of code to be executed when the current scope is exited. It's particularly useful when you want to perform cleaning operations, for example (taken from the Apple docs):

func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
        while let line = try file.readline() {
            // Work with the file.
        // close(file) is called here, at the end of the scope.

Optional binding in a loop

You can use optional binding inside a loop condition, for example suppose you want to go to the last element of a linked list:

var current: Node? = head
while let node = current {
    current = node.next

This collection of tips is of course not complete and I will try to update it as I learn new stuff. If you have other tips yourself or if you want to make a comment feel free to leave it below :)