parameters with optional closures in swift -
i'm using optional closures, can't find way pass on parameter. searched everywhere, tried suggestions, can't work.
my code:
func doalert(title: string , message: string , actions: string , sender: anyobject? , ctlr : uiviewcontroller , seguestring: string? , yesclosure: ()->() = {} , noclosure: ()->() = {} , startclosure: ()->() = {} , endclosure: ()->() = {} ) { if (actions.rangeofstring("ok") != nil { alert.addaction(uialertaction(title: "ok", style: .default ) { action -> void in endclosure() })} } // end function
i want add closure ok, 'self' parameter needed.
something below:
// add func doalert: , okclosure: (anyobject)->() = {} // add action ok (before endclosure: okclosure(sender!)
getting error on first line: anyobject not subtype of ()
if leave anyobject out of first line, getting error: cannot convert expression's type 'anyobject' type '() => ()'
all other trials give me similar 'tuple' errors. how code passing of parameters in optional closures in code?
firstly, use closures argument function, should declare them so:
func myfunc(closure: (int) -> void) { // can call closure so: let myint = 10 closure(myint) }
(as pointed out @airspeed velocity, parenthesis around int
not strictly required because there 1 argument. whether include them personal preference)
secondly, can modify previous function include optional closure, follows: (note ?
, parenthesis around closure indicate closure optional, not return type)
func myfunc(closure: ((int) -> void)?) { // when calling closure need make sure it's not nil. // example: closure?(10) }
thirdly, add default value of nil, looks you're trying = {}
on end of yesclosure: ()->() = {}
, do:
func myfunc(closure: ((int) -> void)? = nil) { // still need make sure it's not nil. if let c = closure { c(10) } }
finally, note, can set names of arguments of closure, can make easier identify you're passing closure when calling it. example:
(note - here parenthesis required around value: int
)
func myfunc(closure: ((value: int) -> void)) { closure(value: 10) }
even more finally, use typealias
. according documentation:
a type alias declaration introduces named alias of existing type program.
here's example of how use closure:
typealias myclosuretype = () -> void func myfunc(closure: myclosuretype) { closure() }
hope helps!