请考虑以下情况: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>'
答案 0 :(得分:1)
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>>