DEV Community

Cover image for Swift: Associated types. Declaration.
Sergey Leschev
Sergey Leschev

Posted on • Edited on

Swift: Associated types. Declaration.

An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: it's a placeholder name of a type to use until the protocol is adopted and the exact type is specified.
This is best explained by a simple code example. Without an associated type, the following protocol would only work for the type we define. In this case: Strings.

protocol StringsCollection {
    var count: Int { get }
    subscript(index: Int) -> String { get }
    mutating func append(_ item: String)
}
Enter fullscreen mode Exit fullscreen mode

If we want to make use of the same logic for a collection of doubles, we would need to recreate a new protocol. Associated types prevent this by putting in a placeholder item:

protocol Collection {
    associatedtype Item
    var count: Int { get }
    subscript(index: Int) -> Item { get }
    mutating func append(_ item: Item)
}
Enter fullscreen mode Exit fullscreen mode

The associated type is defined using the associatedtype keyword and tells the protocol that the subscript return type equals the append item type. This way we allow the protocol to be used with any associated type later defined. An example implementation could look as follows:

struct UppercaseStringsCollection: Collection {

    var container: [String] = []

    var count: Int { container.count }

    mutating func append(_ item: String) {
        guard !container.contains(item) else { return }
        container.append(item.uppercased())
    }

    subscript(index: Int) -> String {
        return container[index]
    }
}
Enter fullscreen mode Exit fullscreen mode

The benefits of an associated type should become visible once you start working with them. They prevent writing duplicate code by making it easier to define a common interface for multiple scenarios. This way, the same logic can be reused for multiple different types, allowing you to write and test logic only once.


Associated types in Swift Protocols.
Declaration
Example
Contraints
Conforming a protocol to a protocol


Contacts
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

🛩ī¸ #startups #management #cto #swift #typescript #database
📧 Email: sergey.leschev@gmail.com
👋 LinkedIn: https://linkedin.com/in/sergeyleschev/
👋 LeetCode: https://leetcode.com/sergeyleschev/
👋 Twitter: https://twitter.com/sergeyleschev
👋 Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev
🖨ī¸ PDF Design Patterns: Download

Top comments (0)