Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Swift how do you simply "make a variable" a RegexComponent?

I have code like this …

func blah() {
  if let r = someString.firstMatch(of: /([abc])(\d{2})$/) {
    blah blah .. String(r.1), String(r.2)
  }
}

Normally with a regex, i’d just keep the regex-guts as a variable.

Hence, something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let RX: RegexComponent = /([abc])(\d{2})$/

func blah() {
  if let r = someString.firstMatch(of: RX) { ..
}

I have completely and absolutely failed to be able to do this, and have searched for hours.

some suggest you need any RegexComponent

let RX: any RegexComponent = /([abc])(\d{2})$/

func blah() {
  if let r = someString.firstMatch(of: RX) { ..
}

But it simply doesn’t work.

the argument of firstMatch#of is undoubtedly a RegexComponent.

How the heck can I make/set a variable that is a RegexComponent ??

>Solution :

This should do the trick:

let RX = /([abc])(\d{2})$/

Now, since it works, you can Alt+click on the var name (RX), and the type inference (ie, type of the variable "deduced" by the compiler) should tell you it’s a Regex<Substring>

So you can write also:

let RX: Regex<Substring> = /([abc])(\d{2})$/

I don’t have the full explanation, since I haven’t played with the new Regex, but I guess it’s because RegexComponent is protocol, so there is no really an init, and there must be something with "literals" (or assimilated).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading