     /// Returns the k nearest `KDTreePoint`s to the search point,
     ///
     /// - Complexity: O(log N).
-    public func nearestK(_ number: Int, to searchElement: Element) -> [Element] {
+    public func nearestK(_ number: Int, to searchElement: Element, where condition: (Element) -> Bool = { _ in true }) -> [Element] {
         var neighbours: Neighbours = Neighbours(goalNumber: number)
-        self.nearestK(to: searchElement, bestValues: &neighbours)
+        self.nearestK(to: searchElement, bestValues: &neighbours, where: condition)
         return neighbours.nearestValues.map { $0.point as! Element }
     }
     
-    fileprivate func nearestK(to searchElement: Element, bestValues: inout Neighbours) {
+
+    fileprivate func nearestK(to searchElement: Element, bestValues: inout Neighbours, where condition: (Element) -> Bool) {
         switch self {
         case let .node(left, value, dim, right):
             let dimensionDifference = value.kdDimension(dim) - searchElement.kdDimension(dim)

            
            //check the best estimate side
            let closerSubtree = isLeftOfValue ? left : right
            closerSubtree.nearestK(to: searchElement, bestValues: &bestValues)

            //check the nodes value
            let currentDistance = value.squaredDistance(to: searchElement)
            bestValues.append(value, distance: currentDistance)

            //if the bestDistance so far intersects the hyperplane at the other side of this value
            //there could be points in the other subtree
            if dimensionDifference*dimensionDifference < bestValues.biggestDistance || !bestValues.full {
                let otherSubtree = isLeftOfValue ? right : left
                otherSubtree.nearestK(to: searchElement, bestValues: &bestValues)
            }
        case .leaf: break
        }

    /// Optional parameter 'maxDistance' if you are not interested in neighbours beyond a specified distance
    ///
    /// - Complexity: O(N log N).
    public func nearest(to element: Element, maxDistance: Double = Double.infinity, condition: (Element) -> Bool = { _ in true }) -> Element? {
        guard !self.isEmpty else { return nil }
        
        return nearest(to: element, bestValue: nil, bestDistance: maxDistance, condition: condition).bestValue
    }
    
    fileprivate func nearest(to searchElement: Element, bestValue: Element?, bestDistance: Double, condition: (Element) -> Bool) -> (bestValue: Element?, bestDistance: Double) {
        switch self {
        case .leaf: break
        case let .node(.leaf, value, _, .leaf) where condition(value):
            let currentDistance = value.squaredDistance(to: searchElement)
            if currentDistance < bestDistance { return (value, currentDistance) }
        case let .node(left, value, dim, right):
