Now that we’ve seen how an associated type could work in a real case example it’s time to dive a bit deeper into the available possibilities.
Let’s continue with our example showed earlier for defining a Collection
:
protocol Collection {
associatedtype Item
var count: Int { get }
subscript(index: Int) -> Item { get }
mutating func append(_ item: Item)
}
What if we want to compare the appending item to any of the existing items before inserting? We need to have a way to compare for equity.
We can do this by constraining the associated type to, in this case, the Equatableprotocol
:
protocol Collection {
// The associated type now needs to conform to Equatable
associatedtype Item: Equatable
var count: Int { get }
subscript(index: Int) -> Item { get }
mutating func append(_ item: Item)
}
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)