> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Filter Numeric Range

> Lets users refine results between two numeric values using a slider.

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">iOS</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/range-slider/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/range-slider/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/range-slider/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/api-reference/widgets/range-slider/ios"><span className="afs-option-name">iOS</span><span className="afs-option-lib">InstantSearch iOS</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/api-reference/widgets/range-slider/android"><span className="afs-option-name">Android</span><span className="afs-option-lib">InstantSearch Android</span></a></li>
    </ul>
  </div>
</div>

```swift Signature theme={"system"}
NumberRangeConnector<Number>(
  filterState: FilterState,
  attribute: Attribute,
  bounds: ClosedRange<Number>?,
  range: ClosedRange<Number>,
  operator: RefinementOperator,
  groupName: String?,
  controller: NumberRangeController
)
```

<Card title="Explore example code" icon="github" href="https://github.com/algolia/instantsearch-ios/tree/master/Examples/Showcase">
  Browse the Filter Numeric Range example code on GitHub.
</Card>

## About this widget

`Filter Numeric Range` is a filtering component made to filter between two numeric values.
The most common interface for this is a slider.

## Examples

Instantiate a `NumberRangeConnector` and launch an initial search on its searcher.

```swift Swift icon=code theme={"system"}
let searcher = HitsSearcher(appID: "YourApplicationID",
                            apiKey: "YourApiKey",
                            indexName: "YourIndexName")
let filterState: FilterState = .init()

let numberRangeController: RangeSliderController = .init(rangeSlider: .init())

let numericRangeConnector: NumberRangeConnector<Double> = .init(searcher: searcher,
                                                                filterState: filterState,
                                                                attribute: "price",
                                                                controller: numberRangeController)

searcher.search()
```

## Parameters

<ParamField body="searcher" type="HitsSearcher" required>
  The [`Searcher`](/doc/api-reference/widgets/instantsearch/ios) that handles your searches.
</ParamField>

<ParamField body="filterState" type="FilterState" required>
  The [`FilterState`](/doc/api-reference/widgets/filter-state/ios) that holds your filters.
</ParamField>

<ParamField body="attribute" type="Attribute" required>
  The attribute to filter.
</ParamField>

<ParamField body="interactor" type="NumberRangeInteractor<Number>" post={["default: .init()"]} required>
  The logic applied to the numeric range.
</ParamField>

<ParamField body="bounds" type="ClosedRange<Number>?" post={["default: nil"]}>
  The nounds limiting the max and the min value of the range.
</ParamField>

<ParamField body="range" type="ClosedRange<Number>" post={["default: nil"]}>
  The initial range value.
</ParamField>

<ParamField body="operator" type="RefinementOperator" post={["default: .and"]}>
  Whether the filter is added to a conjuncitve(`and`) or a disjuncitve (`or`) group in the filter state.
</ParamField>

<ParamField body="groupName" type="String" post={["default: The value of the `attribute` parameter"]}>
  Filter group name in the [`FilterState`](/doc/api-reference/widgets/filter-state/ios)
</ParamField>

<ParamField body="controller" type="NumberRangeController" post={["default: nil"]}>
  The Controller interfacing with a concrete number range view.
</ParamField>

## Low-level API

If you want to fully control the `Filter Numeric Range` components and connect them manually, you can use the following components:

* `Searcher`. The [`Searcher`](/doc/api-reference/widgets/instantsearch/ios) that handles your searches.
* `FilterState`. The current state of the filters.
* `NumberRangeInteractor`. The logic applied to the numeric ranges.
* `NumberRangeController`. The controller that interfaces with a concrete numeric range view.

```swift Swift icon=code theme={"system"}
let searcher = HitsSearcher(appID: "YourApplicationID",
                            apiKey: "YourApiKey",
                            indexName: "YourIndexName")
let filterState: FilterState = .init()

let numericRangeInteractor: NumberRangeInteractor<Double> = .init()
let numberRangeController: RangeSliderController = .init(rangeSlider: .init())

let priceAttribute: Attribute = "price"

searcher.connectFilterState(filterState)

numericRangeInteractor.connectFilterState(filterState, attribute: priceAttribute)
numericRangeInteractor.connectSearcher(searcher, attribute: priceAttribute)
numericRangeInteractor.connectController(numberRangeController)

searcher.search()
```

## Customizing your view

If you want to use a third-party input view,
or you want to introduce some custom behavior to the already provided UIKit component,
you can create your own controller conforming to the `NumberRangeController` protocol.

### Protocol

`func setBounds(_ bounds: ClosedRange<Double>)`:

Function called when the minimum and maximum of numeric filter view have been defined.

`var onRangeChanged: ((ClosedRange<Double>) -> Void)?`

Closure to call when new bounds is set for the numeric range filter.

### Example

Suppose you have a range slider control providing the following API:

```swift Swift icon=code theme={"system"}
class RangeSlider: UIControl {
  var lowerValue: Double
  var upperValue: Double
  var minimumValue: Double
  var maximumValue: Double
}
```

Then, you could implement the `NumberRangeController` including this control as follows:

```swift Swift icon=code theme={"system"}
class RangeSliderController: NumberRangeController {

  let rangeSlider: RangeSlider

  var onRangeChanged: ((ClosedRange<Double>) -> Void)?

  func setBounds(_ bounds: ClosedRange<Double>) {
    rangeSlider.minimumValue = bounds.lowerBound
    rangeSlider.maximumValue = bounds.upperBound
    setItem(bounds)
  }

  func setItem(_ item: ClosedRange<Double>) {
    rangeSlider.lowerValue = item.lowerBound
    rangeSlider.upperValue = item.upperBound
  }

  init(rangeSlider: RangeSlider) {
    self.rangeSlider = rangeSlider
    rangeSlider.addTarget(self, action: #selector(onValueChanged(sender:)), for: [.touchUpInside, .touchUpOutside])
  }

  @objc func onValueChanged(sender: RangeSlider) {
    onRangeChanged?(sender.lowerValue...sender.upperValue)
  }

}
```

### SwiftUI

InstantSearch provides the `NumberRangeObservableController` data model,
which is an implementation of the `NumberRangeController` protocol adapted for usage with SwiftUI.
`NumberRangeObservableController` must be connected to the `NumberRangeConnector` or `NumberRangeConnector` like any other `NumberRangeController` implementation.

The example of the number range view using two `Stepper` components provided by SwiftUI.

```swift Swift icon=code theme={"system"}
struct ContentView: View {

  @ObservedObject var numberRangeController: NumberRangeObservableController<Int>

  var body: some View {
    let range = numberRangeController.range
    VStack{
      Stepper(onIncrement: {
        if let range = makeRange(range.lowerBound+1, range.upperBound) {
          numberRangeController.range = range
        }
      },
      onDecrement: {
        if let range = makeRange(range.lowerBound-1, range.upperBound) {
          numberRangeController.range = range
        }
      },
      label: {
        Text("Lower bound: \(range.lowerBound)")
      })
      Stepper(onIncrement: {
        if let range = makeRange(range.lowerBound, range.upperBound+1) {
          numberRangeController.range = range
        }
      },
      onDecrement: {
        if let range = makeRange(range.lowerBound, range.upperBound-1) {
          numberRangeController.range = range
        }
      },
      label: {
        Text("Upper bound: \(numberRangeController.range.upperBound)")
      })
    }
  }

  func makeRange(_ lowerBound: Int, _ upperBound: Int) -> ClosedRange<Int>? {
    if lowerBound < upperBound &&
       numberRangeController.bounds.contains(lowerBound) &&
       numberRangeController.bounds.contains(upperBound) {
      return lowerBound...upperBound
    } else {
      return nil
    }
  }

}
```

If you prefer to create a custom SwiftUI view that presents the numeric range,
you can directly use the `NumberRangeObservableController` as a data model.
It provides `range` and `bounds` properties to streamline the design process of your custom SwiftUI view.
