Swift相当于我的Objective-C块

时间:2018-01-08 23:34:02

标签: swift closures objective-c-blocks bridging

我似乎无法弄清楚如何从Swift调用Objective-C块!

我有以下Objective-C方法:

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

MyBlock 是:

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

要么抱怨它不能施展:

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

或者当我尝试使用以下任何一种方法从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
    ...
})

我该怎么办?

1 个答案:

答案 0 :(得分:0)

MyBlock 的等效快捷代码:     typedef void(^ MyBlock)(BOOL success,NSDictionary * options)

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

如下:     public typealias MyBlock =(Bool,[String:Any]) - &gt; (空隙)

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

所以当您使用 myMethod 时:

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