<!--
{
  "availability" : [
    "iOS: 27.0.0 -",
    "iPadOS: 27.0.0 -",
    "tvOS: 27.0.0 -",
    "visionOS: 27.0.0 -",
    "watchOS: 27.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "CoreAI",
  "identifier" : "/documentation/CoreAI/NDArray/View/slice(at:)-32gsh",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Core AI",
      "CoreAI"
    ],
    "preciseIdentifier" : "s:13CoreAIRuntime7NDArrayV4ViewV5slice2atAEy_xGSayAC15RangeExpression_pG_tF"
  },
  "title" : "slice(at:)"
}
-->

# slice(at:)

Returns a sub-view with the same rank as this view by slicing the dimensions at the provided ranges.

```
@export(implementation) func slice(at ranges: [any NDArray.RangeExpression]) -> NDArray.View<Element>
```

## Parameters

`ranges`

The range expressions describing where to slice along each dimension.
`ranges.count` must be ≤ `rank`. Unspecified trailing dimensions are assumed to be `.all`.

## Discussion

For example if you have a 2D NDArray and want to compute the sum of a specific row, you can slice that row
and then access a span over it (or use `withUnsafePointer` if not contiguous).

```swift
/// Returns the sum of the given row.
func sumOfRow(
  of view: borrowing NDArray.View<Float>,
  row: Int
) -> Float {
  let rowSlice = view.slice(at: [row])
  let elements = rowSlice.contiguousElements! // contiguous row expected in this case

  var sum: Float = 0
  for i in elements.indices {
    sum += elements[i]
  }
  return sum
}
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)