[Pitch] Extend pattern matching to extract groups from substring matches

I was trying to figure out how I could coax a time duration string into a TimeInterval. If it came in the format of "01h36m22s", I was gonna do something like this:

func durationStringToInterval(_ duration: String) -> TimeInterval? {
   switch duration {
      case "\(let hours)h\(let minutes)m\(let seconds)s":
         guard let hoursInt = Int(hours), let minutesInt = Int(minutes), let secondsInt = Int(seconds) else {
            print("Could not convert durations into ints")
            return nil
         return (hoursInt * 60 * 60) + (minutesInt * 60) + secondsInt
         print("Duration string was in some other format.")
         return nil

... until I realized Swift doesn't have anything to let you pattern match strings with the granularity of being able to extract matching substrings out into their own variables. Would adding something like this to the language be hard to implement? I feel like having a coding paradigm like this to use would be much simpler for newer developers to learn so they can just piggyback off of the switch statement pattern-matching they learn in the Swift beginner docs instead of having to learn NSRegexExpression on top of that. Plus, I intended to do some error handling in the switch default case. Like what if you were getting a duration string from your backend server and you wanted to fail safely in case they change the JSON payloads on the backend or something?

Would it be a huge undertaking to extend it to like an if statement?

if "\(let hours)h\(let minutes)m\(let seconds)s" = durationString {
   print("This movie is \(hours) hours, \(minutes) minutes, & \(seconds) seconds long.")
else {
   print("Invalid duration string.")
Terms of Service

Privacy Policy

Cookie Policy