专门说明一种协议,其中self是一个通用类

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

说我有以下Swift类:

class Foo {}
class Bar<T: Foo> {}

和此协议:

protocol Zip {}

[我正在尝试创建另一个专门用于自身的协议Zap,其中SelfBar,但我想进一步要求Bar的泛型类型是实现FooZip的实例。

protocol Zap where Self: Bar<Foo & Zip> {}

这将导致错误,指出FooZip都必须继承Foo

有没有一种方法可以使用Swift泛型?]​​>

感谢您的帮助。


编辑-预期用途:

如果造成混淆,我深表歉意,但希望它能表明我正在尝试做的事情。

Bar具有对Foo实例的引用,协议Zip具有功能diddleZap具有功能daddle

class Bar<T: Foo> {
  var foo: T
}

protocol Zip {
  func diddle()
}

protocol Zap {
  func daddle()
}

[我想做的是在Zap的扩展名中提供默认实现,以从diddle()调用daddle()时调用函数Bar

extension Zap where Self: Bar<Foo & Zip> {
  func daddle(){
    foo.diddle()
  }
}

最后,这可能只是糟糕的体系结构。

感谢您的回复。


编辑-可能的解决方案

这似乎可以编译,并且可以为我正在尝试的工作工作。

class Foo {}

class Bar<T: Foo> {
    var foo: T

    init(foo: T) {
        self.foo = foo
    }
}

class FooZip: Foo, Zip {
    func diddle() {}
}

protocol Zip {
    func diddle()
}

protocol Zap where Self: Bar<FooZip> {}

extension Zap where Self: Bar<FooZip> {
    func daddle() {
        foo.diddle()
    }
}

谢谢@ kiril-s和发表评论的人。

说我有以下Swift类:类Foo {}类Bar {}和此协议:protocol Zip {}我正在尝试创建另一个专门针对Self的协议Zap ...

swift generics swift-protocols
1个回答
1
投票

不知道其他细节。如果目标是Zap仅接受继承Bar并符合Foo的类型的Zip ...怎么样这样:

extension Foo: Zip {}
protocol Zap where Self: Bar<Foo> {}
© www.soinside.com 2019 - 2024. All rights reserved.