簡體   English   中英

Swift 相當於我的 Objective-C 塊

[英]Swift equivalent of my Objective-C block

我似乎無法弄清楚如何從 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
    ...
})

我該怎么辦?

您的MyBlock的等效 swift 代碼:

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

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

如下:

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

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

所以當你使用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