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: If you want to become a complete senior iOS developer, join this free online crash course starting on October 18th. Learn how to apply truly scalable iOS app architecture patterns through a series of lectures and practical coding sessions. Click to learn more.