xcode 错误:无法使用 Swift + PromiseKit 将类型 '() -> ()' 的值转换为闭包结果类型 'String'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44864563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:06:06  来源:igfitidea点击:

error: cannot convert value of type '() -> ()' to closure result type 'String' using Swift + PromiseKit

swiftxcodepromisekit

提问by John Mike

I am new to promises in Swift and using PromiseKit to try and create a very simple response in a playground and attempt to use it. I have the following code:

我是 Swift 中的 Promise 的新手,并使用 PromiseKit 在操场上尝试创建一个非常简单的响应并尝试使用它。我有以下代码:

//: Playground - noun: a place where people can play

import UIKit
import PromiseKit

func foo(_ error: Bool) -> Promise<String> {
    return Promise { fulfill, reject in
        if (!error) {
            fulfill("foo")
        } else {
            reject(Error(domain:"", code:1, userInfo:nil))
        }
    }
}

foo(true).then { response -> String in {
        print(response)
    }
}

However I get the following error:

但是我收到以下错误:

error: MyPlayground.playground:11:40: error: cannot convert value of type '() -> ()' to closure result type 'String' foo(true).then { response -> String in {

error: MyPlayground.playground:11:40: error: cannot convert value of type '() -> ()' to closure result type 'String' foo(true).then { response -> String in {

采纳答案by aaplmath

The error is being thrown because the closure you're passing to thenpurports to return a String, but no such value is ever returned. Unless you plan on returning a Stringsomewhere in that closure, you need to change the closure's return type to Void, as follows:

抛出错误是因为您传递给的闭包then声称要返回 a String,但从未返回过这样的值。除非您打算String在该闭包中的某处返回 a,否则您需要将闭包的返回类型更改为Void,如下所示:

foo(true).then { response -> Void in
    print(response)
}

Note that closures with the return type Voidcan have their return type omitted. Also, you have an extraneous {in the code in your question (I'm assuming this doesn't exist in your actual code, since it compiles).

请注意,具有返回类型的闭包Void可以省略其返回类型。此外,您{的问题中的代码中有一个无关紧要的内容(我假设这在您的实际代码中不存在,因为它可以编译)。

In addition to that issue, Errorhas no accessible initializers—the initializer you're using in your code actually belongs to NSError, and thus your rejectcall needs to look like:

除了这个问题,Error没有可访问的初始化程序——您在代码中使用的初始化程序实际上属于NSError,因此您的reject调用需要如下所示:

reject(NSError(domain:"", code:1, userInfo:nil))