Jasper Blues
Jasper Blues

Reputation: 28746

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?

Upvotes: 7

Views: 4168

Answers (3)

Mohammad Kamar Shad
Mohammad Kamar Shad

Reputation: 6067

Like to explain it in details,start with your piece of code

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

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

If you want to intimate to caller object after particular moment you need to make a property. var typhoonDefinitionCompletion:BlockTyphoonDefinitionBlock?

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

Upvotes: 1

wint
wint

Reputation: 1286

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

Upvotes: 1

drewag
drewag

Reputation: 94683

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.

Upvotes: 5

Related Questions