简单的Swift泛型难题 [英] simple Swift generics puzzle
问题描述
我试图了解如何在Swift中使用泛型设施做一些简单的事情。我煮了一个问题,我正面临一个简单的难题。想象一下,我想写一个值为的Pair< A,B>
,它有一个 flip 方法,它返回
struct Pair< A,B>< B> {
让a:A
让b:B
init(first:A,second:B){
a = first;
b =秒;
}
func flip() - >对< B,A> {
return Pair(self.b,self.a)
}
}
当我写这个时,我在我试图返回新的翻转对的行上出现错误。 无法将表达式的类型'Pair< A,B>'转换为类型(first:A,second:B)'
我试图做甚么可能吗?
当然这是可能的,因为 Pair< B,A>
在泛型定义的上下文中是完全有效的类型。
您的代码有两个问题,即:
-
您的init方法需要参数标签:
...(first:self.b,second:self.a)
。
-
修正上述错误之后,错误变为'B'不能转换为'A'。编译器显然不推断
flip()
定义中的Pair
指Pair (函数的返回类型)而不是 Pair< A,B>
。因此,您必须显式调用Pair< B,A>(first:self.b,second:self.a)
。
您可能会认为后者不是bug;如果是这样,提交报告!
I'm trying to learn about how to do something simple with the generics facility in Swift. I've boiled one problem that I was facing down to a simple puzzle. Imagine that I want to write a value type Pair<A,B>
that has a flip
method on it that returns a copy of the pair, but with the two values (and their types) reversed.
struct Pair<A, B> {
let a: A
let b: B
init(first: A, second:B) {
a = first;
b = second;
}
func flip() -> Pair<B,A> {
return Pair(self.b,self.a)
}
}
When I write this I get an error on the line where I'm trying to return the new flipped pair. Cannot convert the expression's type 'Pair<A,B>' to type (first: A, second: B)'
Is what I'm trying to do even possible?
Certainly this is possible, since Pair<B,A>
is a perfectly valid type in the context of the generic definition.
There are two problems with your code, namely:
Argument labels are required for your init method:
...(first: self.b, second: self.a)
.After fixing the above, the error becomes "'B' is not convertible to 'A'". The compiler apparently does not infer that
Pair
in the definition offlip()
refers toPair<B,A>
(the function's return type) rather thanPair<A,B>
. So you must explicitly callPair<B,A>(first: self.b, second: self.a)
.
You may or may not consider the latter to be a bug; if so, file a report!
这篇关于简单的Swift泛型难题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!