Search code examples
swiftswift-protocols

What's the point of conforming to an empty protocol in Swift


I'm just working on a codebase where the most classes conform to an empty protocol. Is there any point of doing so? Actually conforming that protocol does nothing.

Edit as reaction to @vacawama's helpful comment : the protocol is only used once

import Foundation

protocol myUrlRequestConfig {}

extension myUrlRequest: myUrlRequestConfig {
    public static func configGetAppConfig() -> URLRequest {
        let request = ....
        return request
    }
}

Solution

  • Our app has three perfectly legitimate uses for an empty protocol:

    • The protocol has an extension with method definitions. The implementation in the extension is automatically injected into any type that adopts the protocol.

    • The protocol has other protocols that adopt it. This allows multiple protocols to be unified under a single head.

    • The protocol marks the adopter as wanting some other type to behave in a certain way. Code can always check whether an object is ThisEmptyProtocol and if it is, can behave differently than if it isn't.