2

我有以下代码:

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'
4

1 回答 1

0

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

版本 1

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

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")
于 2016-09-17T08:01:45.983 回答