调用生成发布程序的泛型函数的正确语法是什么? [英] What is the correct syntax for calling a generic function that generates a publisher?

查看:51
本文介绍了调用生成发布程序的泛型函数的正确语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用以下fetchURL函数的正确语法是什么?

What is the correct syntax of calling the following fetchURL function?

func fetchURL<T: Decodable>(_ url: URL) -> AnyPublisher<T, Error> {
     URLSession.shared.dataTaskPublisher(for: url)
    .map(\.data)
    .decode(type: T.self, decoder: JSONDecoder())
    .eraseToAnyPublisher()
}

我在这里很困惑.

I'm confused here.

let url = URL(string:"http://apple.com")
let publisher = fetchURL<[String].self>(url)????

推荐答案

您无法通过直接指定泛型函数的具体类型来调用它,例如,使用 struct -Swift需要推断出来.

You can't call a generic function by specifying its concrete type directly as you would, for example, with a struct - Swift needs to infer it.

由于 T 仅出现在返回值中,因此Swift只能根据您要为其分配返回值的类型来推断其类型,因此您需要对其进行明确说明:

Since T only appears in the return value, Swift can only infer its type based on the type that you're assigning the return value to, so you need to be explicit about it:

let publisher: AnyPublisher<[String], Error> = fetchURL(url)

这很不方便,因此更好的方法是添加Type参数作为函数的参数,Swift现在将使用该参数来推断具体的类型 T :

This is rather inconvenient, so a better approach is to add a Type parameter as a function's argument, which Swift would now use to infer the concrete type T:

func fetchURL<T: Decodable>(_ t: T.Type, url: URL) -> AnyPublisher<T, Error> {
   // ...
}

let publisher = fetchURL([String].self, url: url)

例如, JSONDecoder.decode > 使用相同的方法

如注释中所建议,您还可以为该类型指定一个默认值,因此,如果可以通过其他方式推断出该类型,则可以将其忽略:

As suggested in comments, you can also specify a default value for the type, so you could omit it if the type can be otherwise inferred:

func fetchURL<T: Decodable>(_ t: T.Type = T.self, url: URL) -> AnyPublisher<T, Error> {
   // ...
}

let pub1: AnyPublisher<[String], Error> = fetchURL(url: url)
let pub2 = fetchURL([String].self, url: url)

这篇关于调用生成发布程序的泛型函数的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆