Sean Sean - 5 months ago 14
iOS Question

Can swift functions have a default completion handler?

In Swift, a function can have default values for a parameter like this:

func init(name: String = "foo"){...}


Can a function with a completion handler have a default value so that when calling a function there is no need to specify the completionHandler as nil, similar to the below?

func foo(completion: (success: Bool) -> void = nil){...}

Answer

You can either do this:

func foo(completion: (success: Bool) -> Void = {_ in }) {
    completion(true)
}

Or this:

func foo(completion: ((success: Bool) -> Void)? = nil) {
    completion?(true)
}
Comments