简体   繁体   中英

Swift equivalent of my Objective-C block

I can't seem to figure out how to call an Objective-C block from Swift!

I have the following Objective-C method:

- (void)myMethod:(NSDictionary *)selection success:(MyBlock)success;

Where MyBlock is:

typedef void(^MyBlock)(BOOL success, NSDictionary* options);

It either complains it can't cast:

"Cannot convert value of type '(Bool, Dictionary<AnyHashable, Any>) -> ()' to expected argument type 'MyBlock!' (aka 'ImplicitlyUnwrappedOptional<(Bool, Optional<Dictionary<AnyHashable, Any>>) -> ()>')"

or I'm getting a SIGABRT when I try to call the method from Swift using any of the following:

myInstance.myMethod(myOptions) { (success, options) in
    ...
}

myInstance.myMethod(myOptions) { (success: Bool, options: Dictionary<AnyHashable, Any>?) in
    ...
}

myInstance.myMethod(myOptions) { (success: Bool!, options: [AnyHashable: Any]?) in
    ...
}

myInstance.myMethod(myOptions, success: { (success, options) in
    ...
})

myInstance.myMethod(myOptions, success: { (success, options) in
    ...
} as MyBlock)

myInstance.myMethod(myOptions, success: { (success: Bool, options: Dictionary<AnyHashable, Any>?) in
    ...
})

myInstance.myMethod(myOptions, success: { (success: Bool!, options: Dictionary<AnyHashable, Any>?) in
    ...
})

myInstance.myMethod(myOptions, success: { (success: Bool!, options: Dictionary<AnyHashable, Any>?) in
        ...
} as MyBlock)

myInstance.myMethod(myOptions, success: { (success: Bool!, options: [AnyHashable: Any]?) in
    ...
})

myInstance.myMethod(myOptions, success: { (success: Bool, options: [AnyHashable: Any]?) in
    ...
})

What do I do?

The equivalent swift code of your MyBlock :

typedef void(^MyBlock)(BOOL success, NSDictionary* options)

- (void)myMethod:(NSDictionary *)selection success:(MyBlock)success;

is as follows:

public typealias MyBlock = (Bool, [String : Any]) -> (Void)

func myMethod(selection: [String : Any], success: MyBlock)

so when you use myMethod for example:

self.myMethod(selection: yourDictionary) { (success, options) -> (Void) in
     //handle here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM