【问题标题】:'self' used inside 'catch' block reachable from super.init call'self' 在 'catch' 块中使用,可从 super.init 调用访问
【发布时间】:2018-10-07 07:37:15
【问题描述】:

此代码未在 Swift 3.3 上编译。它显示消息:'self' used inside 'catch' block accessable from super.init call

public class MyRegex : NSRegularExpression {

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

}

那会是什么?

【问题讨论】:

    标签: swift try-catch nsregularexpression throws


    【解决方案1】:

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

    最简单的解决方案是throwing:

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

    或者作为一个失败的初始化器:

    public class MyRegex : NSRegularExpression {
    
        public init?(pattern: String)  {
            do {
                try super.init(pattern: pattern)
            } catch {
                print("error parsing pattern:", error.localizedDescription)
                return nil
            }
            // ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      相关资源
      最近更新 更多