Home > Back-end >  Swift - protocol method signature based on associatedtype
Swift - protocol method signature based on associatedtype

Time:06-20

Is it in Swift, like in TypeScript possible to define a struct where the methods depend on the generics?

protocol UseCase {
  associatedtype Request
  associatedtype Response
  func execute(controller: () throws -> Request) async throws -> Response
}

If Request is Void, the protocol should return a different method signature.

func execute() async throws -> Response

CodePudding user response:

I would write a protocol extension with where Request == Void:

extension UseCase where Request == Void {
    func execute() async throws -> Response {
        try await execute {}
    }
}

When Request is Void, you can still call execute(controller:), but you can also call the parameterless execute().

When you conform to the protocol, you would need to implement execute(controller:), but this isn't a big problem, since you can just ignore the parameter.

CodePudding user response:

Your contract would be a lie, violating the Liskov substitution principle. You can get around it with an underscore and a default parameter, but I recommend against it.

Also, I think you want Never, not Voidthat's what Apple does.

struct JuiceCase: UseCase {
  func execute(
    controller _: () throws -> Never = { fatalError() }
  ) async throws -> String {
    "           
  • Related