如何在 Swift 中用继承的参数覆盖函数?
我有课:
class ItemA {
var valueA: String?
func setValueA(_ value: String?) {
valueA = value
}
}
class ItemB: ItemA {
var valueB: String?
func setValueB(_ value: String?) {
valueB = value
}
}
// Analog of the abstract class
class ClassA {
func setValues(_ item: ItemA) {
item.setValueA("valueA")
getValues(item) // call getValues from ClassB
}
func getValues(_ item: ItemA) {
abort()
}
}
class ClassB: ClassA {
override func setValues(_ item: ItemB) { // item have type itemB, but extends ItemA
item.setValueB("valueB")
super.setValues(item)
}
override func getValues(_ item: ItemA) {
let item = item as! ItemB
let array = [item.valueA, item.valueB]
print(array)
}
}
我的目标是获得以下结果:
let itemB = ItemB()
ClassB().setValues(itemB)
// print ["valueA", "valueB"]
我无法覆盖类中的函数,因为类型不同,而且 Swift 中没有类型继承。我在 ClassB
的 setValues(_ item: ItemB)
方法中收到此错误:
Method does not override any method from its superclass
在 Java 中,这可以使用抽象类和可扩展类型来实现:
abstract class ClassA {
<T extends ItemA> void setValues(T item) {
item.setValueA("valueA");
getValues(item);
}
abstract void getValues(MainItem item);
}
最佳答案
正确答案取决于泛型:
class ItemA {
var valueA: String?
func setValueA(_ value: String?) {
valueA = value
}
}
class ItemB: ItemA {
var valueB: String?
func setValueB(_ value: String?) {
valueB = value
}
}
// Analog of the abstract class
class ClassA {
func setValues<T : ItemA>(_ item: T) {
item.setValueA("valueA")
getValues(item) // call getValues from ClassB
}
func getValues(_ item: ItemA) {
abort()
}
}
class ClassB: ClassA {
override func setValues<T : ItemB>(_ item: T) {
// item have type itemB, but extends ItemA
item.setValueB("valueB")
super.setValues(item)
}
override func getValues(_ item: ItemA) {
let item = item as! ItemB
let array = [item.valueA, item.valueB]
print(array)
}
}
检查一下!如果您想打印非可选值,请将它们展开。
let itemB = ItemB()
ClassB().setValues(itemB)
// print ["valueA", "valueB"]
关于swift - 如何使用各种继承参数覆盖函数(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55635813/