我從swift類調用目標c中的方法。我的目標c方法是期望在NSNumber格式的數字。我沒有在swift中定義數字類型,但仍然收到以下消息。有什麼辦法可以解決這個問題嗎?無法將Float類型的值轉換爲預期的參數類型NSNumber
- (void)getPercentageMatch:(NSString *)answer listOfAnswers:(NSArray *)validAnswers completionBlock:(void(^)(BOOL isSuccess, NSNumber *percent))completionBlock {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:answer forKey:@"myanswer"];
[params setValue:validAnswers forKey:@"answers"];
NSMutableURLRequest *req = [AuthorizationHandler createAuthReq:@"POST" path:@"validateAnswer" params:params];
AFJSONRequestOperation *op = [[AFJSONRequestOperation alloc] initWithRequest:req];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *responseheaders = (NSDictionary *)responseObject;
if (completionBlock) {
completionBlock(true, [responseheaders valueForKey:@"percentage"]);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionBlock) {
completionBlock(false, 0);
}
}];
[op start];
return;
}
我也被迫結束塊鑄字
as! completionBlock(Bool, NSNumber)
但這並不工作。
我是新來的迅速和任何教程/指針可以理解的:)
編輯1:
當我修改完成塊
let completionBlock = { (isSuccess, percent) in
print("-------", isSuccess, percent)
}
MTRestkitManager.instance().getPercentageMatch(_:text, listOfAnswers:validAnswers, completionBlock:completionBlock)
我沒有得到任何錯誤。但是,如果我再次添加一個輕微的修改,則會出現錯誤。
爲什麼行爲變化?
編輯2: 繼柯林的解決方案,進行了如下修改
@IBAction func submitButtonTapped(_ sender: Any) {
answerTextView.resignFirstResponder()
if answerTextView.textColor == UIColor.lightGray {
ZUtility.showError(NSLocalizedString("Please enter answer before submitting", comment: ""))
return;
}
if answerTextView.text.isEmpty {
ZUtility.showError(NSLocalizedString("Please enter answer before submitting", comment: ""))
setPlaceholderText()
return;
}
let text = answerTextView.text as String
let completionBlock = { (isSuccess, percent:NSNumber) -> (Void) in
self.handleAnswer(isSuccess: isSuccess, percent: Float(percent))
}
MTRestkitManager.instance().getPercentageMatch(_:text, listOfAnswers:validAnswers, completionBlock:completionBlock)
}
在我收到一個錯誤的最後一行:無法將類型的價值「(BOOL,NSNumber的) - >(無效)」 '?!((BOOL,NSNumber的) - >(無效)' 預期參數類型
發佈你的swift代碼不是圖像.. – Bilal
這是如何有所作爲? –
看到這個... https://meta.stackoverflow.com/a/285557/1825618 – Bilal