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
    }
}