我正在關注 IOS 的 Braintree 檔案。
它建議實作這樣的方法(快速):
func onLookupComplete(_ request: BTThreeDSecureRequest, result: BTThreeDSecureLookup, next: @escaping () -> Void) {
// Optionally inspect the lookup result and prepare UI if a challenge is required
next()
}
我的目標代碼是一些用于反應原生模塊的目標 C,其中函式定義如下:
RCT_EXPORT_METHOD(getAddressLine1: (NSString *) address
callback: (RCTResponseSenderBlock) callback)
{ ... }
目標 C 模塊(尤其是“下一個:@escaping”部分)的快速實作等效于什么?
注意:這是Braintree 檔案
謝謝
uj5u.com熱心網友回復:
next: @escaping () -> Void
所以() -> Void,這被稱為閉包,而在 Objective-C 中,它被稱為塊。
@escaping意味著該方法將在呼叫閉包之前“結束”。換句話說,如果你有func myMethod(escaped: @escaping () -> Void) -> Bool,并且如果你寫
let methodOutput = myMethod(escaped: {
print("here closure has been called")
}
print(methodOutput)
print(methodOutput)有很大的機會(但不一定)在print("here closure has been called"). 通常是因為它是異步的。
現在,這是一個UIView知道如何翻譯它們的方法示例:
在斯威夫特:
class func animate(
withDuration duration: TimeInterval,
animations: @escaping () -> Void
)
在Objective-C 中:
(void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations;
現在,我已經說過異步呼叫它不是強制性的,因為我們可以用偽代碼來描繪這個場景:
func myMethod(escaped: @escaping () -> Void)) {
if canBeDone == false { //In Swift, a guard is better
escaped()
} else {
doLongAsyncProcess(onDidFinished: { escaped() })
}
}
如果canBeDone為false,則直接呼叫閉包(synchrone),否則稍后呼叫(asynchrone)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507541.html
