gpt4 book ai didi

ios - 无法使用自定义类返回类型覆盖方法

转载 作者:行者123 更新时间:2023-11-28 12:48:02 25 4
gpt4 key购买 nike

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

最佳答案

除了编译器不支持之外没有其他原因。要覆盖父类(super class)扩展中定义的方法,您必须声明它与 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()
}

}

关于ios - 无法使用自定义类返回类型覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com