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)