swift - 泛型的扩展在 swift 中被限制为另一个泛型

标签 swift generics

考虑以下情况,其中 T1T2可以是任何类型。

class Foo<T1> {}
class Bar<T2> {}

我需要 Foo 的扩展其中 T1Bar<T2> .这看起来很明显,但问题却很模棱两可——我找不到太多这方面的信息。编译器提示以下消息:

extension Foo where T1:Bar {} // Error: reference to generic type 'Bar' requires arguments in <...>
extension Foo where T1:Bar<T2> {} // Error: use of undeclared type 'T2'

extension Foo where T1:Bar<Any> {
    func test() { Swift.print(self) }
}

let foo = Foo<Bar<NSObject>>()
foo.test() // Error: 'Bar<NSObject>' is not a subtype of 'Bar<Any>'

最佳答案

class Foo<T1> {}
class Bar<T2> {}

extension Foo where T1:Bar<NSObject> { // instead of Any
    func test() { Swift.print(self) }
}

let foo = Foo<Bar<NSObject>>()
foo.test()
// output: CfsdikgLiC.Foo<CfsdikgLiC.Bar<Foundation.NSObject>>

可以吗?或者其他版本:

class Foo<T1> {}
class Bar<T2> {}

extension Foo where T1:Bar<Any> { 
    func test() { Swift.print(self) }
}

let foo = Foo<Bar<Any>>() // instead of NSObject
foo.test()
// output: T8fT4XJI7R.Foo<T8fT4XJI7R.Bar<Any>>

关于swift - 泛型的扩展在 swift 中被限制为另一个泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837840/

相关文章:

ios - 如何删除导航 Controller 后退按钮标题?

ios - 如何将实例方法作为闭包参数传​​递给另一个函数?

Java 泛型比较器

generics - 作为使用关联类型的特征的结构成员

ios - 如何使用arrayLiteral初始化IndexPath

快速,旋转 ImageView 并将旋转 ImageView 设置为 uibutton

swift - 如何检测多行字符串中每一行的第一个索引?

generics - 使用静态分派(dispatch)返回特征类型

c# - 泛型类装饰器的copy方法如何实现?

java - 使用通用数组的 ArrayList 转换 ArrayList.toArray()