Apply Async Text Edits Without Overwriting New Typing

Select a paragraph, tap “Rewrite,” and keep typing while the result arrives. That is a reasonable thing for a person to do. An editor that replaces the newer paragraph has a different definition of reasonable.

SwiftUI can tell us which text is selected. The more interesting problem is deciding whether a delayed result still has permission to change the document.

We’ll build a small editor that snapshots a selection, prepares a replacement asynchronously, previews it, and applies it only if the document is still the same revision. The same pattern works for translation, formatting, spelling suggestions, or model-generated edits. The example uses an uppercase transformation so the document-safety behavior is visible without a service account or a particularly opinionated model.

The API gap closed; the editing problem remains

An older Stack Overflow question asked how to obtain selected text from TextEditor. It now has an answer using the selection binding added in iOS 18. This is an answered question with an interesting next step, not a claim that SwiftUI still requires a UIKit wrapper.

Majid’s text-input article demonstrates the selection APIs. We can build on that idea by turning a selection into an explicit edit proposal with a limited lifetime.

Apple’s TextSelection represents an insertion point, a selected range, or multiple selected ranges. For this iOS example, we accept one nonempty range. We do not silently pick one piece of a multiselection.

This is a plain String editor. For styled content, our AttributedString editor uses a different selection type and mutation API.

Give every proposal two identities

A proposal needs to answer two questions:

  • Does it belong to the current document revision?
  • Does it belong to the current request?

The first check rejects results after typing, paste, undo, or a programmatic document replacement. The second rejects an older request even if a newer request started without changing the text.

Cancellation helps stop unnecessary work, but Swift’s cancellation is cooperative. A service can finish after cancellation. A proposal therefore has to prove it is current when it arrives and again when the person taps Apply.

Here is the complete model. Put the three Swift blocks in this article into the same Swift file in an iOS 18-or-later app, using Swift 6.2 or later.

import Foundation

nonisolated struct SelectionEditSession: Sendable {
    struct Ticket: Sendable {
        fileprivate let revision: UUID
        fileprivate let request: UUID
        fileprivate let prefix: String
        let selectedText: String
        fileprivate let suffix: String
    }

    struct Proposal: Sendable {
        let ticket: Ticket
        let replacement: String
    }

    private(set) var text: String
    private(set) var proposal: Proposal?
    private var revision = UUID()
    private var activeRequest: UUID?

    var isWaiting: Bool { activeRequest != nil && proposal == nil }

    init(text: String) {
        self.text = text
    }

    mutating func replaceText(_ newText: String) {
        text = newText
        revision = UUID()
        discard()
    }

    mutating func begin(in range: Range<String.Index>) -> Ticket? {
        guard !range.isEmpty else { return nil }
        let request = UUID()
        let ticket = Ticket(
            revision: revision,
            request: request,
            prefix: String(text[..<range.lowerBound]),
            selectedText: String(text[range]),
            suffix: String(text[range.upperBound...])
        )
        activeRequest = request
        proposal = nil
        return ticket
    }

    func isCurrent(_ ticket: Ticket) -> Bool {
        ticket.revision == revision && ticket.request == activeRequest
    }

    @discardableResult
    mutating func offer(_ replacement: String, for ticket: Ticket) -> Bool {
        guard isCurrent(ticket) else { return false }
        proposal = Proposal(ticket: ticket, replacement: replacement)
        return true
    }

    @discardableResult
    mutating func applyProposal() -> Bool {
        guard let proposal, isCurrent(proposal.ticket) else { return false }
        let updated = proposal.ticket.prefix
            + proposal.replacement
            + proposal.ticket.suffix
        replaceText(updated)
        return true
    }

    mutating func discard() {
        activeRequest = nil
        proposal = nil
    }
}

begin(in:) has an important precondition: the range must come from the current text. The view will capture it synchronously from its selection binding. This helper is not a validator for arbitrary indices from another string.

Immediately copying the prefix, selection, and suffix means no String.Index survives into the asynchronous operation. Applying a valid proposal constructs a new string from those snapshots. We never reach into a mutated string with an old index.

Copying the surrounding text is a reasonable tradeoff for a small note. For a large document, measure the copying cost and consider a document-operation model before capturing the entire prefix and suffix for every suggestion.

That matters for Unicode. Swift strings use extended grapheme clusters, and a visible character need not occupy one byte or one UTF-16 code unit. Native string slicing preserves the selected contents without inventing integer offsets. Swift’s strings and characters guide explains the indexing and canonical-equivalence rules.

A revision is stronger than comparing the text

Every call to replaceText changes the revision, even when the new string compares equal to the old one.

Suppose someone starts a request, edits the paragraph, and then undoes that edit. A comparison against the original text could accept the old request. Our policy rejects it: the person has edited since the request began, so they should request another preview.

There is also a less obvious case. Canonically equivalent Unicode strings can compare equal while using different underlying representations. Equality is useful for comparing text; it is not an edit-history token.

The tradeoff is deliberate. Even an unrelated edit elsewhere in the document invalidates the proposal. That is conservative and easy to explain. Preserving a proposal across unrelated edits requires a range-mapping or document-operation system. This small example does not pretend to be a collaborative editor.

Use an async transformation with an obvious result

The stand-in below adds a short delay and uppercases only the selected text. The delay makes it easy to type while work is pending; it is not a debounce policy.

@concurrent
func makeDemoReplacement(_ selectedText: String) async throws -> String {
    try await Task.sleep(for: .milliseconds(600))
    try Task.checkCancellation()
    return selectedText.uppercased()
}

@concurrent, introduced in Swift 6.2, makes the function run away from the caller’s actor. It does not create an unstructured task by itself. That isolation contract is described in SE-0461.

When substituting a translator or formatter, pass it the copied selection and return a replacement string. Keep network credentials, model availability, output limits, and service-specific errors inside that operation. The operation does not get to mutate the editor.

Put the checks at both ends of the wait

Here is the complete view. It owns one task and cancels it when a new request starts, the document changes, or the view disappears.

import SwiftUI

@available(iOS 18.0, macOS 15.0, *)
@MainActor
struct SelectionRewriteEditor: View {
    @State private var editor = SelectionEditSession(
        text: "Select a few words, preview the replacement, then keep typing."
    )
    @State private var selection: TextSelection?
    @State private var work: Task<Void, Never>?
    @State private var message = ""

    private var textBinding: Binding<String> {
        Binding(
            get: { editor.text },
            set: { newText in
                work?.cancel()
                work = nil
                editor.replaceText(newText)
                selection = nil
                message = ""
            }
        )
    }

    private var selectedRange: Range<String.Index>? {
        guard let selection,
            case .selection(let range) = selection.indices,
            !range.isEmpty
        else { return nil }
        return range
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            TextEditor(text: textBinding, selection: $selection)
                .frame(minHeight: 220)
                .accessibilityLabel("Document")

            Button(editor.isWaiting ? "Restart preview" : "Preview uppercase") {
                startPreview()
            }
            .disabled(selectedRange == nil)

            if editor.isWaiting {
                HStack {
                    ProgressView()
                    Text("Preparing a replacement…")
                    Button("Cancel") { cancelPreview() }
                }
            }

            if let proposal = editor.proposal {
                GroupBox("Proposed replacement") {
                    VStack(alignment: .leading, spacing: 12) {
                        Text("Original selection").font(.caption)
                        Text(verbatim: proposal.ticket.selectedText)
                        Divider()
                        Text("Replacement").font(.caption)
                        Text(verbatim: proposal.replacement.isEmpty
                            ? "(Empty: removes the selected text)"
                            : proposal.replacement)
                        HStack {
                            Button("Apply to original selection") {
                                if editor.applyProposal() {
                                    selection = nil
                                    message = "Replacement applied."
                                }
                            }
                            Button("Discard") { cancelPreview() }
                        }
                    }
                    .frame(maxWidth: .infinity, alignment: .leading)
                }
            }

            if !message.isEmpty {
                Text(verbatim: message)
                    .foregroundStyle(.secondary)
            }
        }
        .padding()
        .onDisappear { cancelPreview() }
    }

    private func startPreview() {
        guard let range = selectedRange,
            let ticket = editor.begin(in: range)
        else { return }
        work?.cancel()
        message = ""

        work = Task {
            do {
                let replacement = try await makeDemoReplacement(ticket.selectedText)
                guard !Task.isCancelled else { return }
                if editor.offer(replacement, for: ticket) {
                    work = nil
                }
            } catch {
                guard !Task.isCancelled, editor.isCurrent(ticket) else { return }
                editor.discard()
                work = nil
                message = "The replacement could not be prepared. Try again."
            }
        }
    }

    private func cancelPreview() {
        work?.cancel()
        work = nil
        editor.discard()
    }
}

Set SelectionRewriteEditor() as a destination in your app. Select a word, request the preview, and type before it appears. The document binding immediately changes the revision and clears pending state. Even an operation that ignores cancellation cannot offer that ticket afterward.

Next, let the preview arrive and then type. The same binding removes the proposal. applyProposal() also checks the ticket itself, so correctness does not depend on a button disappearing quickly enough.

There is no suspension between the final check and the mutation. Both run synchronously in the view’s MainActor context. A check before an await, followed by an unchecked write afterward, would reopen the problem.

Be explicit about what changes the target

Moving the caret without changing the document does not invalidate this example’s proposal. The target remains the original selection, which the preview displays and the Apply button names. A later selection is not permission to apply the old replacement at a new location.

Starting another preview changes the request identity. An older completion then fails even if the document revision is unchanged. Dismissing the view calls discard() as well as cancelling the task, so an uncooperative operation has no valid ticket left.

All document writes must go through replaceText. That includes a future undo handler, loading another note, or a remote synchronization update. Do not add a second writable string beside this model and try to synchronize revisions later with onChange.

A production editor may also want focus restoration, undo registration for the applied replacement, and an accessible announcement when a proposal becomes available. Those are separate interaction decisions. The example resets the selection after an edit instead of promising a particular caret placement.

Test an operation that arrives at the worst time

The valuable model tests do not need to sleep. Capture a ticket, make the intervening edit, and then deliver the old result directly. That models a service which completed despite cancellation.

The companion checks cover:

  • An ordinary replacement and a second attempt to apply it.
  • Emoji, combining marks, and a replacement whose length changes.
  • Typing while a result is pending, and typing after its preview arrives.
  • Editing and restoring the original text, including canonically equivalent strings.
  • Two requests finishing in the wrong order without an intervening edit.
  • Discarding a request and then receiving its late result.
  • An insertion point, an empty replacement, and a whole-document selection.

Verified September 30, 2026: all three published Swift blocks compile together with Xcode 27.0 and Swift 6.4 for iOS 18, including MainActor default isolation and NonisolatedNonsendingByDefault. The model checks execute against the exact first block; the demo transformation is also compiled and exercised. Native selection gestures, keyboard behavior, and VoiceOver still require simulator or device interaction testing.

A useful suggestion should survive review. It should not survive the document it was meant to edit.