Articles, podcasts and news about Swift development, by John Sundell.

Checking whether an element was inserted into a set

Published on 05 Dec 2018
Discover page available: The Standard Library

Swift’s Set returns a tuple every time we insert a new element, which both contains the element that was inserted, but also — and this is really useful — a Bool indicating whether the element was actually inserted or not.

A great example of using tuples as lightweight types.

// BEFORE

class FavoriteManager {
    private var favoriteIDs = Set<Article.ID>()
    
    func markArticleAsFavorite(_ article: Article) -> Outcome {
        guard !favoriteIDs.contains(article.id) else {
            return .failure
        }
        
        favoriteIDs.insert(article.id)
        return .success
    }
}

// AFTER

class FavoriteManager {
    private var favoriteIDs = Set<Article.ID>()
    
    func markArticleAsFavorite(_ article: Article) -> Outcome {
        let wasInserted = favoriteIDs.insert(article.id).inserted
        return wasInserted ? .success : .failure
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.