user3168237
user3168237

Reputation:

Why can't i ignore a closure parameter with a default function in Swift?

I have a method with a closure as a parameter that defaults to a 'dummy' function if no closure is provided. However, whenever I try omitting the parameter with the default, the compiler throws the error:

Missing argument for parameter 'closureFuncWithDefault' in call
Insert 'parameterClosureFuncWithDefault: <#(object) -> Void#>'

My code is as follows:

func functionWithDefault (object: SCNReferenceNode = SCNReferenceNode(),
              closureWithDefault: @escaping (_ object: SCNReferenceNode)->Void = { _ in return }) {

    otherClassInstance.loadObject (object, loadedHandler: { [unowned self] loadedObject in DispatchQueue.main.async {

            self.otherMethod (loadedObject)
            closureWithDefault (virtualObject)
        }
    })

}

Then from somewhere else:

// some code

var objectThing = SCNReferenceNode (URL: ..... )

//
// code block...
//

functionWithDefault (object: objectThing) // <-- This throws the error.

SCN class and such things are not the relevant things, rather, the proper way to have a closure parameter with a default and being able to use it.

Upvotes: 0

Views: 1133

Answers (1)

Rob
Rob

Reputation: 437412

The common syntax is to use an optional closure, calling it with ?:

func functionWithDefault (object: SCNReferenceNode = SCNReferenceNode(), closure: @escaping ((_ object: SCNReferenceNode) -> Void)? = nil) {
    otherClassInstance.loadObject (object) { [unowned self] loadedObject in 
        DispatchQueue.main.async {
            self.otherMethod (loadedObject)
            closure?(virtualObject)
        }
    }
}

Or, considering a simpler example:

func foo(completion: @escaping ((Bool) -> Void)? = nil) {
    performAsynchronousTask { success in
        completion?(success)
    }
}

And then you can call this as either:

foo()

Or

foo { success in
    if success { ... } else { ... }
}

Upvotes: 1

Related Questions