考虑以下情况,其中 T1
和 T2
可以是任何类型。
class Foo<T1> {}
class Bar<T2> {}
我需要 Foo
的扩展其中 T1
是Bar<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/