【问题标题】:Cannot override method with a custom class return type无法使用自定义类返回类型覆盖方法
【发布时间】:2016-05-25 02:37:50
【问题描述】:

有什么方法可以用来覆盖返回自定义类的方法吗?当我尝试使用自定义类作为返回类型覆盖任何方法时,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

带有错误信息:

来自扩展的声明还不能被覆盖

【问题讨论】:

标签: ios swift inheritance overriding


【解决方案1】:

除了编译器不支持它之外,没有其他原因。要覆盖定义在超类扩展中的方法,您必须声明它与 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 Parent: UIViewController {

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

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

}

【讨论】:

  • 不错且直截了当的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多