In some cases you want to conform a protocol to another protocol that defines an associated type.
protocol CollectionSlice: Collection {
func prefix(_ maxLength: Int) -> CollectionSlice
}
Itβs not uncommon to run into an error like this:
Protocol βCollectionSliceβ can only be used as a generic constraint because it has Self or associated type requirements
This is because the compiler canβt make sure that the returned CollectionSlice
will result in the same underlying associated type as the defined protocol. Therefore, we need to setup a constraint that makes sure both types are equal:
protocol CollectionSlice: Collection {
associatedtype Slice: CollectionSlice where Slice.Item == Item
func prefix(_ maxLength: Int) -> Slice
}
Implementors of this protocol are now required to return a slice of the same type as its parent collection:
extension UppercaseStringsCollection: CollectionSlice {
func prefix(_ maxLength: Int) -> UppercaseStringsCollection {
var collection = UppercaseStringsCollection()
for index in 0..<min(maxLength, count) {
collection.append(self[index])
}
return collection
}
}
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)