简体   繁体   English

为什么Swift不能通过扩展泛型where子句调用函数?

[英]Why Swift calls function not from an extension generic where clause?

If I call function (eg funcB) from a class that have extension where clause directly all works as expected. 如果我从具有扩展where子句的类中调用函数(例如funcB),则所有子句都可以按预期工作。

But if I call some another function (eg funcA) of a class and called function use funcB inside I see a result from original funcB not from extension. 但是,如果我调用一个类的另一个函数(例如funcA),并在函数内部使用funcB,我会看到原始funcB而不是扩展的结果。

Code sample: 代码示例:

class Bar {

}

class Foo<T> {

    func funcA() {
        funcB()
    }

    func funcB() {
        print("Parent without clause")
    }

}

extension Foo where T: Bar {

    func funcB() {
        print("Parent + clause")
    }

}

Foo<Any>().funcB()

Foo<Bar>().funcB()

print("--")

Foo<Any>().funcA()

Foo<Bar>().funcA()

Output: 输出:

Parent without clause 父母无条款

Parent + clause 父母+条款

-- -

Parent without clause 父母无条款

Parent without clause 父母无条款

I want to call different implementation depending on parent of T and send T to a second class. 我想根据T的父级调用不同的实现,然后将T发送给第二个类。

If T is child of Bar, use Class<T: Bar> else return nil. 如果T是Bar的子级,则使用Class <T:Bar>,否则返回nil。

To have some kind of "abstract" class behavior, you can use a protocol instead of generic class. 要具有某种“抽象”类行为,可以使用协议而不是通用类。

Something like this: 像这样:

class Bar: FooProtocol {
}

class Foo: FooProtocol {
}

protocol FooProtocol {
    func funcA()
    func funcB()
}

extension FooProtocol {
    func funcA() {
        funcB()
    }

    func funcB() {
        print("Parent without clause")
    }
}

extension FooProtocol where Self: Bar {
    func funcB() {
        print("Parent + clause")
    }
}

Here I have used a default implementation for the FooProtocol but you can define the functions int the Foo class and Bar class depending on what you want. 在这里,我使用了FooProtocol的默认实现,但是您可以根据需要定义int Foo类和Bar类的函数。 Then you will have this result: 然后,您将得到以下结果:

    let bar = Bar()
    bar.funcA() // Parent + clause
    bar.funcB() // Parent + clause

    let foo = Foo()
    foo.funcA() // Parent without clause
    foo.funcB() // Parent without clause

This is a correct behaviour for current Swift implementation. 对于当前的Swift实现,这是正确的行为。

https://bugs.swift.org/browse/SR-10549 https://bugs.swift.org/browse/SR-10549

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM