无法使用自定义类返回类型

时间:2016-05-25 02:37:50

标签: ios swift inheritance override

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

错误消息:

  

扩展声明无法覆盖

1 个答案:

答案 0 :(得分:2)

除编译器之外没有任何理由不支持它。要覆盖超类扩展中定义的方法,必须声明它与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 snafus,是在Parent类中定义这些方法(不在扩展内):

class Parent: UIViewController {

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

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

}