gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:57:53 24 4
gpt4 key购买 nike

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

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

}

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

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

为什么?

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

有人可以帮助我吗?

谢谢。

最佳答案

也许我错了,但恕我直言,你的泛型闭包需要参数类型 () -> Int,但后来你实际上在做: () -> 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

关于Swift 2 使用通用闭包参数声明函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com