从super.init调用可以在'catch'块内使用'self'

cri*_*mad 6 try-catch throws nsregularexpression swift

此代码未在Swift 3.3上编译.它显示了消息:'self'在super.init调用可以访问的'catch'块中使用

public class MyRegex : NSRegularExpression {

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

}
Run Code Online (Sandbox Code Playgroud)

那可能是什么?

Mar*_*n R 9

如果super.init失败则对象未完全初始化,在这种情况下,初始化程序也必须失败.

最简单的解决方案是throw:

public class MyRegex : NSRegularExpression {

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

}
Run Code Online (Sandbox Code Playgroud)

或者作为可用的初始化程序:

public class MyRegex : NSRegularExpression {

    public init?(pattern: String)  {
        do {
            try super.init(pattern: pattern)
        } catch {
            print("error parsing pattern:", error.localizedDescription)
            return nil
        }
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)