Has Swift's concurrency model gone too far?

I believe all internal state is compiled before any usage can occur, so Regex is mostly save to use from different threads except that it can include arbitrary code that may not be sendable:

I think Regex being non-sendable is a similar issue to many of its uses being throwing. Since Regex is closer to an arbitrary parser than a finite state automaton, you have a lot less guarantees.

1 Like

So what's the best way to store a regex that a bunch of methods share? For example:

class Foo {
    static let regex = /[+|-]?[0-9]+/
    func a() { use(Self.regex) }
    func b() { use(Self.regex) }
    func c() { use(Self.regex) }
    ...
}

Could it be that regex literals are de-duplicated at compile time the way strings usually are? And so you could use it as an instance let without a big performance hit. Maybe?

1 Like

Following the topic I linked to, you can use nonisolated(unsafe) when your regex is not using custom code that is not sendable.

nonisolated(unsafe) static let regex = /[+|-]?[0-9]+/

Otherwise, isolating it to an actor is often a good choice:

@MainActor static let regex = /[+|-]?[0-9]+/
3 Likes

Thank you. I appreciate the suggestions.

@ibex10 is right about the lack of docs. I think I just need to understand the model better.