我有以下代码:
protocol NextType {
associatedtype Value
associatedtype NextResult
var value: Value? { get }
func next<U>(param: U) -> NextResult
}
struct Something<Value>: NextType {
var value: Value?
func next<U>(param: U) -> Something<Value> {
return Something()
}
}
现在,问题出现在Something
next
的实施中。我想返回Something<U>
而不是Something<Value>
。
但是当我这样做时,我收到了以下错误。
type 'Something<Value>' does not conform to protocol 'NextType'
protocol requires nested type 'Value'
答案 0 :(得分:0)
我测试了以下代码并进行编译(Xcode 7.3 - Swift 2.2)。在这种状态下,它们不是很有用,但我希望它能帮助您找到所需的最终版本。
由于Something
是使用V
定义的,因此我认为您不能仅返回Something<U>
。但您可以使用Something
和U
重新定义V
,如下所示:
protocol NextType {
associatedtype Value
associatedtype NextResult
var value: Value? { get }
func next<U>(param: U) -> NextResult
}
struct Something<V, U>: NextType {
typealias Value = V
typealias NextResult = Something<V, U>
var value: Value?
func next<U>(param: U) -> NextResult {
return NextResult()
}
}
let x = Something<Int, String>()
let y = x.value
let z = x.next("next")
或者只使用Something
定义V
:
protocol NextType {
associatedtype Value
associatedtype NextResult
var value: Value? { get }
func next<U>(param: U) -> NextResult
}
struct Something<V>: NextType {
typealias Value = V
typealias NextResult = Something<V>
var value: Value?
func next<V>(param: V) -> NextResult {
return NextResult()
}
}
let x = Something<String>()
let y = x.value
let z = x.next("next")