Protocol Having generic function and associatedType

﹥>﹥吖頭↗ 提交于 2019-12-09 20:17:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!