1

Consider this code:

func testA(){} func testB(value:Int){} func testC(value:String){} var someTest:Any = testA 

How do you case-match on a variable holding a closure to find the correct one so you can call it?

switch someTest{ case let test where test:() -> Void: test() case let test where test:(value:Int) -> Void: test(4) case let test where test:(value:String) -> Void: test("A") } 

Is something like this possible?

7
  • 2
    You want e.g case let test as (String) -> Void, compare stackoverflow.com/q/38980403/2976878 Commented Mar 11, 2018 at 17:22
  • 2
    Though depending on your use case, you may want to consider using an enum with associated values for each function type; then you can exhaustively switch without having to type-cast. Commented Mar 11, 2018 at 17:24
  • @Alexander: That Q&A does not cover matching against closures, I wonder if this is worth a separate answer (preferably from Hamish due to his initial comment) Commented Mar 11, 2018 at 18:13
  • Duh! as not where. Of course! Hamish, post that as an answer and I’ll accept it. Commented Mar 11, 2018 at 18:51
  • 1
    Haha yes I did, and fair enough, i'll reopen Commented Mar 11, 2018 at 20:28

1 Answer 1

1

Closure types are subject to the same switching patterns that any other types are:

switch someClosure { case let runnable as () -> Void: runnable() case let intConsumer as (Int) -> Void: intConsumer(4) case let stringConsumer as (String) -> Void: stringConsumer("A") } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.