Should Regex be Sendable?

In the mean time, you can declare regex constants as nonisolated(unsafe).

// Compiling with -swift-version 6

nonisolated(unsafe) // <---
public let MyRegex = /[0-9]+/

actor MyActor {
  func matches(_ input: String) -> Bool {
    input.firstMatch(of: MyRegex) != nil  // okay.
  }
}

This also works for regex builders, which is where you might add custom logic via closures.

// Compiling with -swift-version 6

import RegexBuilder

nonisolated(unsafe) // <---
public let MyRegex = Regex {
  Capture(
    {
      OneOrMore { .digit }
    },
    transform: { Double($0) }
  )
}

actor MyActor {
  func match(_ input: String) -> Double? {
    input.firstMatch(of: MyRegex)?.1  // okay.
  }
}

This means you are promising that your regex does not have non-sendable shared state (it's unsafe, so the compiler isn't checking for you), but for most regexes that should be an easy determination to make. Especially if you just have a Regex literal - it's not even possible for it to contain non-sendable shared state.

Eventually it would be nice if the compiler checked this for you and made it safely non-isolated.

3 Likes