DEV Community

Cover image for Swift: Conforming a protocol to a protocol.
Sergey Leschev
Sergey Leschev

Posted on • Updated on

Swift: Conforming a protocol to a protocol.

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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)