I am building a tokeniser, and would like to hold this as a struct, passing in a locale during initiation.
Here's the gist of what I would want to write:
struct Tokeniser {
private let locale: Locale
private let integerRegex: Regex
init(locale: Locale) {
self.locale: Locale
self.integerRegex = Regex {
Capture {
.localizedInteger(locale: locale)
} transform: {
Token.number($0)
}
}
}
func parse(text: String) -> Token {
if let match = try integerRegex.firstMatch(in: text) {
//... other code here
}
}
\\...other code here
}
As Regex is generic the compiler suggests to set the integerRegex
's type to Regex<Any>
, but this triggers another set of compiler issues that I have not been able to figure out what the type should be. So then I tried to write something like this (inspired by SwiftUI):
var integerRegex: some Regex {
Capture {
.localizedInteger(locale: locale)
} transform: {
Token.number($0)
}
}
But again, the compiler prompts me to enter Regex<Any>.
The only way I have to be able to get the struct to compiler is to create lazy variables, which then have the side effect that I have to mark my functions as mutable, which have downstream issues when they are called from with SwiftUI structs.
lazy var integerRegex = Regex {
Capture {
.localizedInteger(locale: locale)
}
}
mutating func parse(text: String) -> Token {
if let match = try integerRegex.firstMatch(in: text) {
}
}
How can I code this?