简单的Swift泛型难题 [英] simple Swift generics puzzle

查看:79
本文介绍了简单的Swift泛型难题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在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> 在泛型定义的上下文中是完全有效的类型。



您的代码有两个问题,即:


  1. 您的init方法需要参数标签: ...(first:self.b,second:self.a)

  2. 修正上述错误之后,错误变为'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:

  1. Argument labels are required for your init method: ...(first: self.b, second: self.a).

  2. After fixing the above, the error becomes "'B' is not convertible to 'A'". The compiler apparently does not infer that Pair in the definition of flip() refers to Pair<B,A> (the function's return type) rather than Pair<A,B>. So you must explicitly call Pair<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屋!

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