【问题标题】:Swift Compiler Error when overriding function of subclass inheriting from NSObject that is declared within a function覆盖从函数中声明的 NSObject 继承的子类的函数时出现 Swift 编译器错误
【发布时间】:2015-06-12 08:12:11
【问题描述】:

我得到 Swift 编译器错误 - 由于信号而导致命令失败:分段错误:11" 每当我尝试覆盖从函数中声明的 NSObject 继承的子类的函数时。

我已经尝试过使用不同的类和函数,但我都得到了错误。

  1. 只有在重写函数或
  2. 时才会出现错误
  3. 如果我删除 NSObject,它可以工作,我不会收到错误消息。

有人知道为什么会这样以及为什么从 NSObject 继承会有所不同吗?

例子:

class ParentClass: NSObject {
    func returnFooString() -> String {
        return "foo"
    }
}

//This Fails
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        class childClass: ParentClass {
            override func returnFooString() -> String {
                return "bar"
            }
        }
    }
}

//This Passes
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        class childClass: ParentClass {
           func returnBarString() -> String {
                return "bar"
            }
        }
    }
}

仅当 ParentClass 不继承自 NSObject 时,才会通过重写 returnFooString 函数

【问题讨论】:

    标签: swift class compiler-errors overriding nsobject


    【解决方案1】:

    NSObject 扩展自 Cocoa Class,它有自己的 init 方法。当您删除 NSObject 时,它会变成一个普通的 swift 类,并且不需要 Cocoa Class init。这就是它不报错的原因。

    NSObject的初始化示例

    class MyClass: NSObject {
    
        var someProperty: NSString // no need (!). It will be initialised from controller 
    
        init(fromString string: NSString) {
            self.someProperty = string
            super.init()
        }
    
        convenience override init() {
            self.init(fromString:"John") // calls above mentioned controller with default name
        }        
    }
    

    【讨论】:

    • 是的,我知道,但我没有在上面的代码中初始化任何东西?
    • 我也知道 NSObject 需要一个 Cocoa 类初始化,但为什么会有不同呢?
    【解决方案2】:

    这似乎是旧版本 Swift 中的一个错误。我在 Swift 2.0 中再次测试过,现在已经修复了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多