简体   繁体   English

定义可选通用闭包参数的类型

[英]Defining type of optional generic closure parameter

I want to create an interface, that can be invoked with a generic and a non generic parameter used in the Result type.我想创建一个接口,可以使用Result类型中使用的通用和非通用参数调用该接口。

The API would look like the following: 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...
}

However, when i try to invoke the taskPreparation API, specifying onTyplessComplete as nil但是,当我尝试调用taskPreparation API 时,将onTyplessComplete指定为nil

taskPreparation(onTypedComplete: nil, 
                onTyplessComplete: { result in // Do something ... })

I receive the error我收到错误

Generic parameter 'T' could not be inferred.无法推断通用参数“T”。

I understand, i have to specify the type of the generic parameter.我明白,我必须指定通用参数的类型。 I have tried to create a dummy decodable parameter, and pass it to the closure.我试图创建一个虚拟可解码参数,并将其传递给闭包。

struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: { (result: Result<DummyDecodable, Error>) in },
                onTyplessComplete: { result in // Do something ... })

But obviously, in this case the onTypedComplete closure is not nil .但显然,在这种情况下onTypedComplete闭包不是nil

Does someone have an idea how could I specify a nil closure and satisfy the type inference too?有人知道我如何指定一个nil闭包并满足类型推断吗?

You would still need the DummyDecodable for this, which is kind of ugly, but at least you are passing a nil value:你仍然需要DummyDecodable为此,这有点丑陋,但至少你传递了一个nil值:

Simply pass ((Result<DummyDecodable, Error>) -> Void)?.none .只需传递((Result<DummyDecodable, Error>) -> Void)?.none nil is in fact just a syntactic sugar for Optional<WhateverType>.none . nil实际上只是Optional<WhateverType>.none的语法糖。

struct DummyDecodable: Decodable {}
taskPreparation(onTypedComplete: ((Result<DummyDecodable, Error>) -> Void)?.none,
                onTyplessComplete: { result in /* Do something ...*/ })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM