First, to use closure as an argument to a function, you should declare them like this:
func myFunc(closure: (Int) -> Void) {
(As pointed out by @Airspeed Velocity, parentheses around Int are not strictly required because there is only one argument. Do you include them only in your personal setting)
Secondly, you can modify the previous function to enable the optional closure, as follows: (Note the ? And brackets around the closure, indicating that the closure is an optional and not a return type)
func myFunc(closure: ((Int) -> Void)?) { // Now when calling the closure you need to make sure it not nil. // For example: closure?(10) }
Thirdly, to add a default value of nil, which is similar to what you are trying to do with = {} at the end of YesClosure: ()->() = {} , you can do:
func myFunc(closure: ((Int) -> Void)? = nil) { // Still need to make sure it not nil. if let c = closure { c(10) } }
Finally, as a note, you can set the names of the closing arguments, which will make it easier to determine what you pass when closing when called. For instance:
(Note - brackets around value: Int are required here)
func myFunc(closure: ((value: Int) -> Void)) { closure(value: 10) }
Finally, typealias can be used. According to the documentation:
A type alias declaration introduces a named alias of an existing type into your program.
Here is an example of how to use it with closure:
typealias MyClosureType = () -> Void func myFunc(closure: MyClosureType) { closure() }
Hope this helps!