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

时间:2017-07-01 19:18:51

标签: swift xcode promisekit

我是Swift中的新手,并且使用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)
    }
}

但是我收到以下错误:

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

1 个答案:

答案 0 :(得分:1)

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

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

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

除了该问题,Error没有可访问的初始值设定项 - 您在代码中使用的初始值设定项实际上属于NSError,因此您的reject调用需要看起来像:

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