0

I defined a function with a generic closure parameter, like this:

final class Utils {
    static func asyncTask<T>(task: () -> T, main: (res: T) -> Void) {
        dispatch_async(dispatch_get_global_queue(0, 0)) {
            let result = task()
            dispatch_async(dispatch_get_main_queue()) {
                main(res: result)
            }
        }
    }
}

Then, I call it:

Utils.asyncTask({ () -> Int? in
    let rows = self.cursor.db.query(true)
    if !rows.isEmpty {
        return (rows[0] as? BookMark)?.rowId
    }

    return nil
}) { rowId in

}

But I got a compile-time error:

Cannot convert value of type '() -> Int?' to expected argument type '() -> _'

Why?

Swift does supports generic closure as a function parameters, doesn't it?

Anybody can help me?

Thx.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
ruikye
  • 1
  • 2
  • Compiles fine for me – perhaps try cleaning your build folder? Also if you're in a playground, try it in a full project. – Hamish Oct 23 '16 at 18:35

1 Answers1

0

Maybe I'm wrong, but imho your generic closure expects argument type () -> Int, but later on you are actually doing: () -> Int?, which in fact expects optional type.

Maybe other answer will give you some hints: How to determine if a generic is an optional in Swift?

I've tried to simplify your code for the sake of the example:

final class Utils {
    static func asyncTask<T>(task: () -> T, main: (res: T) -> Void) {
        let result = task()
        print("result: \(result)")

        main(res: result)
    }
}

Utils.asyncTask({ () -> Int in
   return 5
}) { rowId in
    print("rowId: \(rowId)")
}

Or like this:

final class Utils {
    static func asyncTask<T>(task: () -> T?, main: (res: T) -> Void) {
        let result = task()
        print("result: \(result)")

        main(res: result!)
    }
}

Utils.asyncTask({ () -> Int? in
   return 5
}) { rowId in
    print("rowId: \(rowId)")
}

It works well with:

Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)
Target: x86_64-apple-macosx10.9
Community
  • 1
  • 1
TekMi
  • 191
  • 6
  • Maybe try to rewrite to: static func asyncTask(task: () -> T?, main: (res: T) -> Void) { – TekMi Oct 23 '16 at 13:16