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
  • 314,917
  • 42
  • 532
  • 579
cristianomad
  • 303
  • 2
  • 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
  • 529,903
  • 94
  • 1,240
  • 1,382