Jasper Blues Jasper Blues - 4 months ago 11
Swift Question

Swift : Define a closure compatible with Objective-C block

I tried to declare a closure matching the following Objective-C block:

typedef void(^TyphoonDefinitionBlock)(TyphoonDefinition *definition);


like this:

var config: TyphoonDefinitionBlock = { (definition: TyphoonDefinition) in
definition.injectProperty("quest", with: nil)
}


. . . and got the following error. (see image).

enter image description here

What's the correct way to do this?

Answer

You need to declare definition as an ImplicitlyUnwrappedOptional (TyphoonDefinition!) because in objective-C it is a pointer that can be nil.

Normal variables (and constants) in swift cannot be nil. They must contain a value.

Comments