Swift 2使用通用闭包参数声明函数

时间:2016-10-23 12:25:19

标签: swift generics

我使用通用闭包参数定义了一个函数,如下所示:

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

然后,我称之为:

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

    return nil
}) { rowId in

}

但是我遇到了编译时错误:

  

无法转换类型'() - &gt;的值INT?预期的参数类型   '() - &gt; _'

为什么呢?

Swift确实支持泛型闭包作为函数参数,不是吗?

任何人都可以帮助我吗?

THX。

1 个答案:

答案 0 :(得分:0)

也许我错了,但是你的泛型闭包需要参数type() - &gt; Int,但后来你实际上在做:() - &gt; Int ?,实际上是期望的可选类型。

也许其他答案会给你一些提示:How to determine if a generic is an optional in Swift?

为了示例,我试图简化您的代码:

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)")
}

或者像这样:

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)")
}

适用于:

Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)
Target: x86_64-apple-macosx10.9
相关问题