问题
I've the following code:
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()
}
}
Now, the problem is in the Something
implementation of next
. I want to return Something<U>
instead of Something<Value>
.
But when I do that I got the following error.
type 'Something<Value>' does not conform to protocol 'NextType'
protocol requires nested type 'Value'
回答1:
I tested the following codes and they compile (Xcode 7.3 - Swift 2.2). In this state they are not very useful, but I hope it helps you to find the final version you need.
Version 1
Since, Something
is defined using V
, I think you can't return just Something<U>
. But you can redefine Something
using U
and V
like this:
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")
Version 2
Or just define Something
using 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")
来源:https://stackoverflow.com/questions/38676174/protocol-having-generic-function-and-associatedtype