<!--
{
  "availability" : [
    "iOS: 26.0.0 -",
    "iPadOS: 26.0.0 -",
    "macCatalyst: 26.0.0 -",
    "macOS: 26.0.0 -",
    "tvOS: 26.0.0 -",
    "visionOS: 26.0.0 -",
    "watchOS: 26.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/AttributedTextSelection/indices(in:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI23AttributedTextSelectionV7indices2inAC7IndicesO10Foundation0C6StringV_tF"
  },
  "title" : "indices(in:)"
}
-->

# indices(in:)

The current text selection indices.

```
func indices(in text: AttributedString) -> AttributedTextSelection.Indices
```

## Return Value

The current selection if valid for the given `text` or a
valid fallback index otherwise.

## Discussion

Always make sure to keep selection and text synchronized. Use
`Foundation/AttributedString/transform(updating:body:)`,
`Foundation/AttributedString/transformAttributes(in:body:)` or
`Foundation/AttributedString/replaceSelection(_:with:)` to do so
automatically.

Reset your selection manually to a newly initialized one after making
programmatic changes to the text where the selection should not just
move with the characters.

```
struct ContentView: View {
    @State private var text = AttributedString()
    @State private var selection = AttributedTextSelection()

    var body: some View {
        TextEditor(text: $text, selection: $selection)

        Button("Insert Date") {
            text.replaceSelection(
                &selection,
                withCharacters: Date.now.formatted())
        }

        Button("Reset") {
            text = "Hello, World!"
            selection = .init(range: text.startIndex..<text.endIndex)
        }
    }
}
```

For more details on attributed string index validity, see
<doc://com.apple.documentation/documentation/Foundation/AttributedString/Index/isValid(within:)-8fw50>.

---

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)