具有通用功能和associatedType的协议

具有通用功能和associatedType的协议

问题描述:

我有以下代码:

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()
    }
}

现在,问题出在nextSomething实现中.我想返回Something<U>而不是Something<Value>.

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'

我测试了以下代码,并进行了编译(Xcode 7.3-Swift 2.2).在这种状态下,它们不是很有用,但是我希望它可以帮助您找到所需的最终版本.

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.

由于Something是使用V定义的,所以我认为您不能仅返回Something<U>.但是您可以像这样使用UV重新定义Something:

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")

版本2

或仅使用V定义Something:

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")