Swift: Definition of closure compatible with Objective-C block

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

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

like this:

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

., and received the following error. (see image).

enter image description here

What is the right way to do this?

+7
objective-c swift
source share
3 answers

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

Normal variables (and constants) in swift cannot be zero. They must contain meaning.

+5
source share

I use typealias taken from http://berzniz.com/post/87924122326/notes-from-coding-in-swift typealias resultBlock = (success: Bool, result: AnyObject!) -> Void

+1
source share

To explain this in detail, start with your code snippet.

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

In Swift, you do it like this typealias TyphoonDefinitionBlock = (definition:TyphoonDefinition?)->Void

If you want to communicate intimately with the caller after a certain point, you need to make a property. var typhoonDefinitionCompletion:BlockTyphoonDefinitionBlock?

you can use typhoonDefinitionCompletion and you can raise a callback message like this. self.typhoonDefinitionCompletion!(definition:passyourtyphoneDefinition)

+1
source share

All Articles