Swift - 无法使用 Result<T, Error> 专门化非通用定义

Swift - Cannot specialize a non-generic definition using Result<T, Error>

正在尝试使用最新的 Swift 5.0 结果 class。制作了一个通用函数,它构建。但是调用它不会编译。这有不同的语法吗? XCode这里不提建议

private func buildTask<T: Decodable>(request:URLRequest, handler: @escaping (Result<T, NetworkError>) -> Void) -> URLSessionDataTask {
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        // logic here....
        let decoder = JSONDecoder()
        if let data = data, let decodedResponse = try? decoder.decode(T.self, from: data) {
            handler(.success(decodedResponse))
        } else {
            handler(.failure(.errorParsing))
        }
    }
    return task
}

// calling method, Compile error here about generic
func test() {
    let url:URL = URL(string: "http://google.com")!
    let request:URLRequest = URLRequest(url: url)
    let task = buildTask<String>(request: request) { (result) in
        switch result {
        case .success:
            print("good")
        case .failure:
            print("bad")
        }
    }
}

// 海报下方的解决方案。

let task = buildTask(request: request) { (result:Result<String, NetworkError>) in
            switch result {
            case .success(let success):
                print("success \(success)")
            case .failure(let error):
                print("error \(error)")
            }
        }

在Swift中调用时不能使用<T>指定泛型类型。泛型方法的类型是根据您传递给它的类型推断出来的。在这种情况下,来自 handler 闭包:

let task = buildTask(request: request) { (result: Result<String, NetworkError>) in

当您指定 result 的类型时,编译器可以推断出闭包的类型,随后还可以推断出方法的泛型类型。