无法使用自定义 class return 类型覆盖方法

Cannot override method with a custom class return type

有什么方法可以用来覆盖 return 自定义 class 的方法吗?当我尝试使用自定义 class 作为 return 类型覆盖任何方法时,Xcode 会抛出一个错误

下面是我的代码:

class CustomClass {
  var name = "myName"
}

class Parent: UIViewController {

  override func viewDidLoad() {
    methodWithNoReturn()
    print(methodWithStringAsReturn())
    methodWithCustomClassAsReturn()
  }

}

extension Parent {

  func methodWithNoReturn() { }
  func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" }
  func methodWithCustomClassAsReturn() -> CustomClass {
    return CustomClass()
  }

}


class Child: Parent {

  override func methodWithNoReturn() {
    print("Can override")
  }

  override func methodWithStringAsReturn() -> String {
    print("Cannot override")
    return "Child methodWithReturn"
  }

  override func methodWithCustomClassAsReturn() -> CustomClass {
    return CustomClass()
  }

}

覆盖此方法时出现错误:

func methodWithCustomClassAsReturn() -> CustomClass

错误信息:

Declarations from extensions cannot be overridden yet

除了编译器不支持之外,没有其他原因。要覆盖在 superclass 的扩展中定义的方法,您必须声明它与 ObjC 兼容:

extension Parent {
    func methodWithNoReturn() { }
    func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" }

    @objc func methodWithCustomClassAsReturn() -> CustomClass {
        return CustomClass()
    }   
}

// This means you must also expose CustomClass to ObjC by making it inherit from NSObject
class CustomClass: NSObject { ... }

不涉及所有 ObjC 混乱的替代方法是在 Parent class(不在扩展内)中定义这些方法:

class Parent: UIViewController {

  override func viewDidLoad() {
    methodWithNoReturn()
    print(methodWithStringAsReturn())
    methodWithCustomClassAsReturn()
  }

  func methodWithNoReturn() { }
  func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" }
  func methodWithCustomClassAsReturn() -> CustomClass {
    return CustomClass()
  }

}