当没有任何参数提供泛型类型时,如何调用泛型Swift函数? [英] How do I call a generic Swift function when none of the arguments provides the generic type?

查看:109
本文介绍了当没有任何参数提供泛型类型时,如何调用泛型Swift函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是在Swift REPL中编译的内容:

  var m:[String:AnyObject] = [:] 
func f< T:AnyObject>(s:String){
m [s] = T.self
}

但是,如果我天真地尝试调用 f(),则:

 let s:String =foo
class Foo {}
f< Foo>(s)
pre>

我得到这个错误:

  repl.swift:7 :1:错误:不能明确地专门化一个通用函数
f< Foo>(s)
^
repl.swift:7:2:注意:当解析这个'<'作为类型参数括号
f< Foo>(s)
^

尝试它没有明确地专门化...

  f(s)

Swift决定我正在尝试做一些更诡异的事情,并且我得到:

  repl.swift:7:1:error:无法将表达式的类型'String'转换为类型'()'
f(s)
^ ~~~

但是,如果我定义一个新函数如下:

  func g< T:AnyObject>(s:String ,t:T){
m [s] = T.self
}

并传入一个虚拟 Foo 实例:

  g(s, Foo())

工作正常:

 > m 
$ R0:[String:AnyObject] = {
[0] = {
key =foo
value = {
instance_type = {}







所以有什么原因让Swift让我首先定义 f()?一旦定义,是否有任何方法可以调用它?






ETA:意识到也可以定义一个明确采用该类型的函数 h< T:AnyObject>(s:String,t:T.Type)。这是事实,Swift允许我定义隐含的版本,我觉得有问题。

解决方案

与其他语言不同,您不能明确用这样的语法指定泛型:

  f (s)

而不是通过参数或返回类型推断实际类型。在你的情况下,你没有提供类型推断的方法来确定 T 是什么。我很遗憾我不知道有什么方法可以使用这个函数。



我的建议是明确地传递 T

  func f m [s] =类型
}

...

f(s,Foo.self)


The following compiles in the Swift REPL:

var m: [String:AnyObject] = [:]
func f<T: AnyObject>(s: String) {
    m[s] = T.self
}

However, if I naively try to invoke f(), thus:

let s: String = "foo"
class Foo {}
f<Foo>(s)

I get this error:

repl.swift:7:1: error: cannot explicitly specialize a generic function
f<Foo>(s)
^
repl.swift:7:2: note: while parsing this '<' as a type parameter bracket
f<Foo>(s)
 ^

If I try it without "explicitly specializing"...

f(s)

Swift decides I'm trying to do something even weirder, and I get:

repl.swift:7:1: error: cannot convert the expression's type 'String' to type '()'
f(s)
^~~~

Meanwhile, however, if I define a new function g() as follows:

func g<T: AnyObject>(s: String, t: T) {
    m[s] = T.self
}

and pass in a dummy Foo instance:

g(s, Foo())

it works fine:

> m
$R0: [String : AnyObject] = {
  [0] = {
    key = "foo"
    value = {
      instance_type = {}
    }
  }
}

So is there a reason Swift lets me define f() in the first place? And once defined, is there any way to invoke it?


ETA: I'm aware it's also possible to define a function h<T: AnyObject>(s: String, t: T.Type) that takes the type explicitly. It's the fact that Swift allows me to define the implicit version that I find questionable.

解决方案

Differently from other languages, you cannot explicitly specify the generic type with a syntax like this:

f<Foo>(s)

instead the actual type is inferred via a parameter or the return type. In your case you are not providing a way for type inference to figure out what T is. And sadly I'm not aware of any way to use that function.

My suggestion is to explicitly pass the type of T:

func f<T: AnyObject>(s: String, type: T.Type) {
    m[s] = type
}

...

f(s, Foo.self)

这篇关于当没有任何参数提供泛型类型时,如何调用泛型Swift函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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