我想创建一个接口(interface),可以使用 Result
类型中使用的泛型和非泛型参数来调用该接口(interface)。
API 如下所示:
struct NonGenericParameter {}
func taskPreparation<T: Decodable>(onTypedComplete: ((Result<T, Error>) -> Void)?,
onTyplessComplete: ((Result<NonGenericParameter, Error>) -> Void)?) {
// Do the neccessery preparation...
if let onComplete = onTypedComplete {
task(onComplete: onComplete)
}
if let onComplete = onTyplessComplete {
task(onComplete: onComplete)
}
}
func task<T: Decodable>(onComplete: @escaping (Result<T, Error>) -> Void) {
// do task...
}
func task(onComplete: @escaping (Result<NonGenericParameter, Error>) -> Void) {
// do task...
}
但是,当我尝试调用 taskPreparation
API 时,将 onTyplessComplete
指定为 nil
taskPreparation(onTypedComplete: nil,
onTyplessComplete: { result in // Do something ... })
我收到错误
Generic parameter 'T' could not be inferred.
我明白,我必须指定泛型参数的类型。我尝试创建一个虚拟的可解码参数,并将其传递给闭包。
struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: { (result: Result<DummyDecodable, Error>) in },
onTyplessComplete: { result in // Do something ... })
但显然,在这种情况下,onTypedComplete
闭包不是 nil
。
有人知道如何指定 nil
闭包并满足类型推断吗?
最佳答案
您仍然需要 DummyDecodable
为此,这有点难看,但至少你传递了 nil
值:
只需通过((Result<DummyDecodable, Error>) -> Void)?.none
。 nil
实际上只是 Optional<WhateverType>.none
的语法糖.
struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: ((Result<DummyDecodable, Error>) -> Void)?.none,
onTyplessComplete: { result in /* Do something ...*/ })
关于ios - 定义可选泛型闭包参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64238553/