0

I would like to have a function returning a function that returns a function with the same signature as the first function. I.e. the function should be able to provide itself as a return value.

Is this possible in swift?

Example (this does not compile!):

typealias nextStep = ((char: CChar) -> nextStep)

func process(char: CChar) -> nextStep {...}
2
  • I think the reason it doesn't compile is because, since nextStep returns nextStep returns nextStep etc., at the end of this chain, nextStep will always return a nextStep which isn't a type. Commented Dec 30, 2014 at 13:10
  • Agree, but is there another way in which the intention of the code can be achieved? Commented Dec 30, 2014 at 13:36

2 Answers 2

2

Thomas's answer should work, but if you want a more typesafe alternative:

struct F {
    let f: (Character) -> F
}

func f(ch: Character) -> F {
    println("I've been called with an \(ch)!")
    return F(f: f)
}

let g = f("a")
let h = g.f("b")
h.f("c")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solution compiles. Don't know yet about runtime, but it is conceptually sound, so it should work just fine.
0

Use Anylike this:

typealias nextStep = ((char: CChar) -> Any)

func process(char: CChar) -> nextStep {
  return process
}

3 Comments

I already accepted this answer, but am now having difficulties in calling the returned function. Any tips on that? (I keep running into the error message "'Any' is not convertible to '(CChar)->Any'")
I added let p = process(CChar()) as nextStep which did compile but got a runtime error when using p the next time. Hmmm...
I guess you better go with Airspeed's solution. This works in any way. I got no idea why the above results in a runtime error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.