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

John Mike picture John Mike · Jul 1, 2017 · Viewed 20.4k times · Source

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:

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 {

Answer

aaplmath picture aaplmath · Jul 1, 2017

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

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

Note that closures with the return type Void can 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).

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

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