具有通用功能和关联类型的协议

2024-01-07

我有以下代码:

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'

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

版本1

Since, Something定义为使用V,我想你不能就这么回来Something<U>。但你可以重新定义Something using U and 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 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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有通用功能和关联类型的协议 的相关文章

随机推荐