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