Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'self' used inside 'catch' block reachable from super.init call

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?

like image 995
cristianomad Avatar asked Apr 26 '18 14:04

cristianomad


1 Answers

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
        }
        // ...
    }
}
like image 86
Martin R Avatar answered Sep 28 '22 08:09

Martin R