通用的扩展在swift中受限于另一个泛型

时间:2017-01-24 19:57:02

标签: 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>'

1 个答案:

答案 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>>