swift - 如何使用各种继承参数覆盖函数(Swift)

标签 swift inheritance overriding abstract-class extends

如何在 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 中没有类型继承。我在 ClassBsetValues(_ 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/

相关文章:

python - 从内置类继承是否正确?

php - Magento : How to override resource file?

ios - 前置摄像头 iOS 的 Firebase MLKit 文本识别失败

c# - 不能使用存储在类型数组中的类型

c++ - 从模板基类覆盖纯虚函数

java - 在覆盖方法中检查 'throws' 的异常

java - 覆盖paint()运行两次

swift - 如何以分组方式拥有两个内容 : dynamic and static

swift - 为什么我的完成处理程序不能与我的 URLSession 一起工作?

ios - 通过位置 iOS 从后台唤醒应用程序