在swift中使用.filter(): error:不能将type '([V]) -> Bool'的值转换为预期参数类型'([_])-> Bool'

时间:2021-10-02 16:35:11

I'm trying to make a Graph class with an outEdges method (just for the purpose of learning Swift, not because I need a Graph class).

我尝试用一个outEdges方法来创建一个图形类(只是为了学习Swift,而不是因为我需要一个图形类)。

I thought I could use .filter() to implement the outEdges method, but I get this error:

我认为我可以使用.filter()来实现outEdges方法,但是我得到了这个错误:

error: cannot convert value of type '([V]) -> Bool' to expected argument type '([_]) -> Bool'
        return edges.filter(leftVertexIs(v))
                            ^~~~~~~~~~~~~~~

With this code:

这段代码:

class Graph<V: Equatable> {
    var edges = [[V]]()

    func addEdge(v1: V, _ v2: V) -> Graph<V> {
        edges.append([v1, v2])
        return self
    }

    func leftVertexIs(v: V) -> (([V]) -> Bool) {
        return {(e: [V]) -> Bool in return e[0] == v}
    }

    func outEdges(v: V) -> [V] {
        return edges.filter(leftVertexIs(v))
    }
}

var g = Graph<Int>()
g.addEdge(2, 4).addEdge(4, 6).addEdge(3, 5).addEdge(2, 7)
g.outEdges(2)

(Note: I moved the filter predicate into a closure to ensure it was working properly)

(注意:我将filter谓词移动到闭包中,以确保它正常工作)

1 个解决方案

#1


2  

edges has the type [[V]], then edges.filter() has the same type and that should be the return type of outEdges:

边缘具有类型[V],然后edgs .filter()具有相同类型,应该是outEdges的返回类型:

func outEdges(v: V) -> [[V]] {
    return edges.filter(leftVertexIs(v))
}

Remark: Instead of storing each edge as a two-element array you should consider to use a tuple (left : V , right : V) or a struct instead.

注意:与其将每条边存储为两个元素数组,不如考虑使用tuple(左:V,右:V)或struct。

#1


2  

edges has the type [[V]], then edges.filter() has the same type and that should be the return type of outEdges:

边缘具有类型[V],然后edgs .filter()具有相同类型,应该是outEdges的返回类型:

func outEdges(v: V) -> [[V]] {
    return edges.filter(leftVertexIs(v))
}

Remark: Instead of storing each edge as a two-element array you should consider to use a tuple (left : V , right : V) or a struct instead.

注意:与其将每条边存储为两个元素数组,不如考虑使用tuple(左:V,右:V)或struct。