DEV Community

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

Posted on • Edited 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)