简体   繁体   English

Swift 相当于我的 Objective-C 块

[英]Swift equivalent of my Objective-C block

I can't seem to figure out how to call an Objective-C block from Swift!我似乎无法弄清楚如何从 Swift 调用 Objective-C 块!

I have the following Objective-C method:我有以下 Objective-C 方法:

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

Where MyBlock is: MyBlock在哪里:

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:或者当我尝试使用以下任一方法从 Swift 调用该方法时收到 SIGABRT:

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 :您的MyBlock的等效 swift 代码:

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:所以当你使用myMethod例如时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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