Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
Jasper Blues Avatar asked Jun 07 '14 03:06

Jasper Blues


People also ask

How do you call a Swift closure in Objective-C?

To simulate it, check your Project-Swift. h file. @objc class TestClass: NSObject { @objc var cancelledStateColorHandler: ((NSColor) -> NSColor)? }

Can you use Swift and Objective-C together?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

What is closure in Objective-C?

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter's type to indicate that the closure is allowed to escape.


2 Answers

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.

like image 67
drewag Avatar answered Oct 06 '22 14:10

drewag


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

like image 44
wint Avatar answered Oct 06 '22 15:10

wint