DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • IoT Communication Protocols for Efficient Device Integration
  • Building Custom Tools With Model Context Protocol
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Contextual AI Integration for Agile Product Teams
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  1. DZone
  2. Coding
  3. Frameworks
  4. Protocol Composition in Swift

Protocol Composition in Swift

Learn about two different approaches to achieve cleaner code through separate cohesive protocols in a Swift application.

By 
Marco Santarossa user avatar
Marco Santarossa
·
Nov. 02, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
6.7K Views

Join the DZone community and get the full member experience.

Join For Free

If we want to write clean code, we should split our interface into little protocols with cohesive properties and methods. The problem of having several protocols is that we often need to use some of them together. For example, we may want to declare a variable of a type which combines some protocols together. The solution is using protocol composition.

In this article, we’re going to see two approaches to achieve protocol composition in Swift.

Happy reading!

Getting Started

Let’s consider the following protocol:

protocol FileHandlerType {
    func read() -> String
    func write(_ value: String)
}

It has a method to return the content of a file and a method to write a String inside a file.

The problem of this protocol is that it breaks the Interface Segregation Principle. FileHandlerType is a fat interface; it contains methods that are not cohesive. If we want to follow the SOLID principles, we should get rid of FileHandlerType and split it into two protocols, like these:

protocol FileHandlerReadable {
    func read() -> String
}

protocol FileHandlerWritable {
    func write(_ value: String)
}

This refactoring brings us a problem. Before the refactoring, we could declare a variable of type FileHandlerType and use its methods read and write:

struct FileHandler: FileHandlerType {
    func read() -> String {
        return ""
    }

    func write(_ value: String) {

    }
}

let handler: FileHandlerType = FileHandler()

handler.read()
handler.write("Hello World")

After the refactoring, we no longer have FileHandlerType. We have two protocols. How can we declare a variable of a type which combines FileHandlerReadable and FileHandlerWritable? Protocol composition can save our day.

In the next sections, we’re going to see two approaches to manage protocol composition. A basic one—which is a generic object-oriented programming approach—and a more “Swifty” one.

Basic Approach

This approach is very generic. We can use it also in other languages, like Java.

We can create an empty protocol FileHandlerType which extends both FileHandlerReadable and FileHandlerWritable:

protocol FileHandlerType: FileHandlerReadable, FileHandlerWritable {
}

In this way, FileHandlerType inherits the methods of both FileHandlerReadable and FileHandlerWritable. At this point, we can finally declare a variable of type FileHandlerType:

struct FileHandler: FileHandlerType {
    func read() -> String {
        return ""
    }

    func write(_ value: String) {

    }
}

let handler: FileHandlerType = FileHandler()

handler.read()
handler.write("Hello World")

Note: We may have the concern that this approach is similar to having only a single protocol FileHandlerType like this:

protocol FileHandlerType {
    func read() -> String
    func write(_ value: String)
}

The difference is that, with this approach, we don’t break Interface Segregation Principle. We still have an interface split into two protocols: FileHandlerReadable and FileHandlerWritable.

Swifty Approach

If you don’t like Basic Approach, there is good news for you. Swift provides a more “Swifty” way to achieve protocol composition.

If we want to combine two or more protocols together, we can use the operator &. We can combine FileHandlerReadable and FileHandlerWritable like this:

struct FileHandler: FileHandlerReadable, FileHandlerWritable {
    func read() -> String {
        return ""
    }

    func write(_ value: String) {

    }
}

let handler: FileHandlerReadable & FileHandlerWritable = FileHandler()

handler.read()
handler.write("Hello World")

This approach has a downside. If we combine several protocols, we start having messy code:

let variable: ProtocolA & ProtocolB & ProtocolC & ProtocolD & ProtocolE

For this reason, I would suggest you use a typealias to clean the declaration of our variables:

typealias FileHandlerType = FileHandlerReadable & FileHandlerWritable

struct FileHandler: FileHandlerType {
    func read() -> String {
        return ""
    }

    func write(_ value: String) {

    }
}

let handler: FileHandlerType = FileHandler()

handler.read()
handler.write("Hello World")

Note: You can see a real use of this approach in the file StorageContext.swift of the open source library StorageKit.

Conclusion

I usually prefer using the Swifty Approach. In this way, I can avoid creating a new empty protocol only to combine different protocols together. Then, I always use a typealias to clean the concatenation of protocols.

Protocol (object-oriented programming) Swift (programming language)

Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • IoT Communication Protocols for Efficient Device Integration
  • Building Custom Tools With Model Context Protocol
  • OPC-UA and MQTT: A Guide to Protocols, Python Implementations

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: