无法将Float类型的值转换为预期的参数类型NSNumber

时间:2017-07-14 06:54:17

标签: objective-c swift xcode nsnumber

我在swift类中调用了目标c中的方法。我的目标c方法是期望NSNumber格式的数字。我没有在swift中定义数字类型但仍然得到以下消息。有什么方法可以解决这个问题吗?

enter image description here

- (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)

但这不起作用。

我是swift的新手,任何教程/指针都会受到赞赏:)

编辑1:

当我修改完成块

let completionBlock = { (isSuccess, percent) in
        print("-------", isSuccess, percent)
    }
    MTRestkitManager.instance().getPercentageMatch(_:text, listOfAnswers:validAnswers, completionBlock:completionBlock)

我没有收到任何错误。但是,如果我再次添加一个小修改,我会收到错误。

enter image description here

为什么行为会改变?

编辑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?) - >(Void)!'

1 个答案:

答案 0 :(得分:0)

显然,Float是从handleAnsewer()的{​​{1}}函数推断出来的。您应该手动在self中定义正确的类型:

completionBlock

请记住,您无法在Swift中自动进行类型转换,您应该调用显式初始值设定项,例如let completionBlock = { (isSuccess, percent: NSNumber?) in self.handleAnsewer(isSuccess: isSuccess, percent: percent.floatValue ?? 0) } NSNumber(value: myFloat))。

P.S。我打赌你来自python:)