Swift 覆盖从函数内声明的 NSObject 继承的子类的函数时出现编译器错误

Swift Compiler Error when overriding function of subclass inheriting from NSObject that is declared within a function

我得到 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"
            }
        }
    }
}

重写returnFooString函数只有在ParentClass不继承自NSObject时才会通过

NSObjectCocoa Class 扩展而来,它有自己的初始化方法。当您删除 NSObject 时,它会变成正常的 swift class 并且不需要 Cocoa Class init。这就是它不报错的原因。

Initialization Sample of 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
    }        
}

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