[英]How do I stop a generic function in Swift matching a Tuple type?
I have these two methods我有这两种方法
func doSomething<T>(_ completion: (T) -> Void) { ... }
func doSomething<T, U>(_ completion: (T, U) -> Void) { ... }
Unfortunately, this won't compile when I try to use the version with two generic types.不幸的是,当我尝试使用具有两种泛型类型的版本时,这将无法编译。
doSomething { (value1: String, value2: Int) in ... }
Because it's ambiguous between the second doSomething<String, Int>
and the first doSomething<(String, Int)>
ie a single generic type which is a tuple containing the two strings.因为它在第二个
doSomething<String, Int>
和第一个doSomething<(String, Int)>
之间是不明确的,即一个泛型类型,它是一个包含两个字符串的元组。
Obviously, I can call these methods two different names?显然,我可以将这些方法称为两个不同的名称吗? Is there a way to resolve this ambiguity without doing that?
有没有办法在不这样做的情况下解决这种歧义?
( doSomething as ( (String, Int) -> Void ) -> Void ) { value1, value2 in }
You could make a type alias…你可以做一个类型别名…
typealias DoSomething<T, U> = ( (T, U) -> Void ) -> Void
(doSomething as DoSomething) { (value1: String, value2: Int) in }
(doSomething as DoSomething<String, Int>) { _ = ($0, $1) }
…but type aliases can't be overloaded, so you'd need one for every function overload but one. …但是类型别名不能被重载,所以你需要一个为每个 function 重载但一个。 And there'd be no point in that;
那没有任何意义; giving the functions different names would be simpler.
给函数起不同的名字会更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.