6

This code is not compiling on Swift 3.3. It's showing the message: 'self' used inside 'catch' block reachable from super.init call

public class MyRegex : NSRegularExpression {

    public init(pattern: String) {
        do {
            try super.init(pattern: pattern)
        } catch {
            print("error parsing pattern")
        }
    }

}

What could that be?

rmaddy
  • 298,130
  • 40
  • 468
  • 517
cristianomad
  • 193
  • 1
  • 9

1 Answers1

11

The object is not fully initialized if super.init fails, in that case your initializer must fail as well.

The simplest solution would be to make it throwing:

public class MyRegex : NSRegularExpression {

    public init(pattern: String) throws {
        try super.init(pattern: pattern)
        // ...
    }

}

Or as a failable initializer:

public class MyRegex : NSRegularExpression {

    public init?(pattern: String)  {
        do {
            try super.init(pattern: pattern)
        } catch {
            print("error parsing pattern:", error.localizedDescription)
            return nil
        }
        // ...
    }
}
Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248