协议具有泛型函数和associatedType

时间:2016-07-30 16:38:09

标签: swift generics protocols swift-protocols associated-types

我有以下代码:

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'

1 个答案:

答案 0 :(得分:0)

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

版本1

由于Something是使用V定义的,因此我认为您不能仅返回Something<U>。但您可以使用SomethingU重新定义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")

版本2

或者只使用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")