协议具有泛型函数和associatedType

问题描述 投票:2回答:1

我有以下代码:

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'
swift generics protocols swift-protocols associated-types
1个回答
0
投票

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

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

Version 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")
© www.soinside.com 2019 - 2024. All rights reserved.