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) {
        return collection
Enter fullscreen mode Exit fullscreen mode

Associated types in Swift Protocols.
Conforming a protocol to a protocol

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:
๐Ÿ‘‹ LinkedIn:
๐Ÿ‘‹ LeetCode:
๐Ÿ‘‹ Twitter:
๐Ÿ‘‹ Github:
๐ŸŒŽ Website:
๐ŸŒŽ Reddit:
๐ŸŒŽ Quora:
๐ŸŒŽ Medium:
๐Ÿ–จ๏ธ PDF Design Patterns: Download

Top comments (0)