Manuel
Manuel

Reputation: 15042

How to use a protocol function as block definition?

Here a function b calls a and passes a completion block:

func a(completion: (_ succeeded: Bool)) {
    completion(true)
}

func b() {
    a() { succeeded in
        ...
    }
}

Can I use a protocol function definition to define the block?

Something like this (which does not work):

protocol P {
    func c(succeeded: Bool)
}

func a(completion: P) {
    completion.c(succeeded: true)
}

func b() {
    a() { c(succeeded) in
        ...
    }
}

Note: I am not looking for the protocol/delegate concept.

Upvotes: 0

Views: 145

Answers (2)

Josh Homann
Josh Homann

Reputation: 16327

The issue with using a protocol here is that functions cannot conform to a protocol, only classes, enums and structs can conform to a protocol. So you either need one of these types or an instance of one of these types, but then the instance seems superfluous. If you really want to do it the protocol way here is an example with static conformance on an enum:

import UIKit

protocol Callable {
  static func call(someString: String, someInt: Int)
}

enum MyCallable: Callable {
  static func call(someString: String, someInt: Int) {
    print(someString, someInt)
  }
}

func someFunction<T: Callable>(callable: T.Type) {
  callable.call(someString: "a",someInt: 1)
}

someFunction(callable: MyCallable.self)

Upvotes: 1

Josh Homann
Josh Homann

Reputation: 16327

You can use a labeled tuple to give yourself argument labels if that is what you are after. Here is a playground example:

import UIKit

typealias MyArguements = (someInt: Int, someString: String)

func someFunction( completion: @escaping (MyArguements) -> Void) {
  completion((someInt: 1, someString: "a"))
}

someFunction { tuple in
  let (someInt, someString) = tuple
  print(someInt, someString)
}

Upvotes: 1

Related Questions