I believe I'm running Swift 5.7 from the command line on macOS Monterey, 12.4, and that Swift 5.7 implements the new Regex class and regex literal syntax, but It doesn't seem to. I need help resolving this so that I can use the 5.7 regex feature.
For the following file "parse.swift". Swift didn't seem to understand the Swift 5.7 regex literal: /.../ syntax; it generated errors it shouldn't for what was clearly legitimate regex pattern, so I tried a different approach and discovered it doesn't recognize the new Regex class itself.
let pattern = #"^ ,([A-Z][A-Z])([0-9][0-9]),(.*?),(.*?) "#
let regex = try! Regex(pattern)
$ swift parse.swift < somefile
parse.swift:3:18: error: cannot find 'Regex' in scope let regex = try! Regex(pattern) ^~~~~
Is there something I need to import or do differently?
This is the version it says I'm running:
$ swift --version
Apple Swift version 5.7-dev (LLVM eecf02df5133efe, Swift ad06e7d7251311a) Target: arm64-apple-macosx12.0
I selected the 5.7 version of Swift by exporting the following from ~/.zshrc
Using Swift snapshots in macOS CLI is always a bit of a struggle. Beta Xcode would be easier.
Anyway, here is how to make it work:
import _StringProcessing to parse.swift.
$TOOLCHAIN_DIR/usr/bin/swiftc parse.swift \
-sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk \
-Xfrontend -enable-experimental-string-processing \
-sdk ... is for finding libobjc which is needed but not included in snapshot.
-Xfrontend options are to bypass beta restrictions.
_RegexParser dylibs are not available in the SDK and your code needs to find them at runtime.
Note you should not need this with
-enable-experimental-string-processing (soon to be enabled by default in [5.7] Enable string processing by default. by rxwei · Pull Request #59623 · apple/swift · GitHub).
To use the bare slash
/.../ regex syntax you will need to pass the
-enable-bare-slash-regex compiler flag, as the syntax is potentially source breaking. See swift-evolution/0354-regex-literals.md at main · apple/swift-evolution · GitHub for more info.
@yonihemi, speaking of "easier with Xcode beta", I have that (14.0 beta 4), but I still can't use regex on my macOS 12.4 machine. Is there no way around this? Doesn't the beta come with the necessary runtimes?
Specifically, I get "'Regex' is only available in macOS 13.0 or newer".
Edit: It does work for iOS playgrounds, for instance, but also not for macOS playgrounds.