【问题标题】:Protocol Having generic function and associatedType具有通用功能和关联类型的协议
【发布时间】:2016-12-05 04:41:35
【问题描述】:

我有以下代码:

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()
    }
}

现在,问题在于nextSomething 实现。我想返回 Something&lt;U&gt; 而不是 Something&lt;Value&gt;

但是当我这样做时,我得到了以下错误。

type 'Something<Value>' does not conform to protocol 'NextType'
protocol requires nested type 'Value'

【问题讨论】:

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


    【解决方案1】:

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

    版本 1

    由于Something 是使用V 定义的,我认为您不能只返回Something&lt;U&gt;。但是您可以像这样使用UV 重新定义Something

    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

    或者只是使用V定义Something

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多