Swift 中的多态性 - 函数重写

问题描述 投票:0回答:1

有一个基类:

class Base {
    func foo<S: Base>(to value: S) {
        print("Base class foo")
    }
}

以及从 Base 派生的:

class One: Base {
    func foo(to value: Two) {
        print("foo: Two")
    }
}

class Two: Base {
    func foo(to value: One) {
        print("foo: One")
    }
}

class Three: Base {
    func foo(to value: One) {
        print("foo: One")
    }
}

使用示例:

var sample: Base = One()

sample.foo(Two())    // expected "foo: Two"
sample.foo(Three())  // expected Base class implementation to be called "Base class foo"

这个想法是在派生类的实现存在或默认为使用泛型的

One
类实现的情况下,从
Two
Three
Base
被称为“专用”func 变体。我的尝试是添加关键字
override
但编译器报告派生类的函数不会覆盖任何内容,并且每次只调用基类 func...

swift generics polymorphism
1个回答
0
投票
My attempt was to add the keyword override but the compiler reports the derived class's function does not override anything and only the base class func is called every single time

因为您没有提供与基类中的方法相同的通用签名。如果您不放置相同的签名,编译器将不允许您使用

override
关键字。它应该是这样的:

class Base {
    func foo<S: Base>(to value: S) {
        print("Base class foo")
    }
}

class One: Base {
    override func foo<S: Base>(to value: S) {
        guard let value = value as? Two else {
            super.foo(to: value)
            return
        }
        print("foo: Two")
    }
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.