[英]Cannot override method with a custom class return type
Is there any method i can use to override a method which returns custom class? 我可以使用任何方法来覆盖返回自定义类的方法吗? When i tried to override any method with a custom class as a return type, Xcode throws me an error 当我尝试使用自定义类重写任何方法作为返回类型时,Xcode抛出错误
Below are my codes: 以下是我的代码:
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()
}
}
The error is when overriding this method: 错误是在重写此方法时:
func methodWithCustomClassAsReturn() -> CustomClass func methodWithCustomClassAsReturn()-> CustomClass
with error message: 错误消息:
Declarations from extensions cannot be overridden yet 来自扩展的声明还不能被覆盖
No reason other than the compiler doesn't support it yet. 除编译器不支持外,没有其他原因。 To override a method defined in an extension to the superclass, you must declare it ObjC-compatible: 要覆盖超类扩展中定义的方法,必须将其声明为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 { ... }
The alternative, without involving all the ObjC snafus is to define these methods in the Parent
class (not inside an extension): 不涉及所有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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.