fferri
fferri

Reputation: 18940

using .filter() in swift: error: cannot convert value of type '([V]) -> Bool' to expected argument type '([_]) -> Bool'

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).

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

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)

Upvotes: 2

Views: 729

Answers (1)

Martin R
Martin R

Reputation: 539685

edges has the type [[V]], then edges.filter() has the same type and that should be the return type of 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.

Upvotes: 2

Related Questions