简体   繁体   English

推断完成块中的通用类型

[英]Infer Generic Type In Completion Block

I have a function: 我有一个功能:

static func requestArray<T>(completion: @escaping (_ result: Result<[T], Error>) -> ()) {

}

That is called like this: 像这样被称为:

MyClass.requestArray() { result in
    switch result {
        case .success(let array):
            break
        case .failure(let error):
            break
        }
}

However, this doesn't work because it can't infer the generic type T. How can I alter my code so that it does recognise what type T should be? 但是,这不起作用,因为它无法推断出通用类型T。如何更改我的代码,使其能够识别T应该是什么类型? (Assume array should be of type [String] ) (假设array的类型应为[String]

It's generally more convenient if the API moves the type into the signature, in order to simplify the closure: 如果将API将类型移动到签名中,通常会更加方便,以简化闭包:

static func requestArray<T>(of: T.Type, completion: @escaping (_ result: Result<[T], Error>) -> ()) { }

When done this way, the call becomes: 通过这种方式完成后,调用将变为:

MyClass.requestArray(of: String.self) { result in
    switch result {
        case .success(let array):
            break
        case .failure(let error):
            break
        }
}

This approach also works nicely when T is a return type. T是返回类型时,此方法也很好用。 See Codeable for a good example of this approach in methods like decode(_;from:) . 有关Codeable的一个很好的例子,请参见Codeable ,如decode(_;from:)

You have explicitly declare the type of result in the completion handler when you call the function: 调用函数时,已在完成处理程序中显式声明了result类型:

MyClass.requestArray() { (result: Result<[String], Error>) in
    switch result {
    case .success(let array):
        break
    case .failure(let error):
        break
    }
}

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

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