0

Studying Swift grammar declaration of closure. I'm having a problem with:

let add: (Int, Int) -> Int 
add = { (a: Int, b: Int) -> Int in
    return a + b
}

error:

variables currently must have an initial value when entered at the top level of the REPL var add: (Int, Int) -> Int

1 Answer 1

1

Swift does not have separate variable declarations without assignments (assigning nil to an optional would be the closest thing), so the easiest fix would be:

let add: (Int, Int) -> Int = { (a: Int, b: Int) -> Int in
   return a + b
}

As correctly pointed out by the commenters and as noted in the error message, my claim is only true at the top level of the Read-Eval-Print-Loop (REPL).

Sign up to request clarification or add additional context in comments.

2 Comments

This is not completely true. Swift does have separate variable declarations without assignment. You just cannot do that at the top level. You could do that without problems in a console application or in a function.
This applies only to the REPL. Perfectly legal: gist.github.com/woolsweater/503c12cd91b9e9573e0ddadec7b02c0d

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.