【问题标题】:Swift Associated type constraintsSwift 关联类型约束
【发布时间】:2019-09-17 14:37:49
【问题描述】:

我有两个协议,每个协议都定义了一个关联类型。其中一个协议需要定义另一个协议类型的变量,其中它们都具有相同类型的关联类型。是否有可能以某种方式推断关联类型的类型?

protocol A {
    associatedtype AModel
    var b: B { get }
}

protocol B {
    associatedtype BModel
    func doAnother(anotherModel: BModel)
}

这是我尝试但没有成功的方法

protocol A {
    associatedtype AModel
    associatedtype TypedB = B where B.BModel == AModel
    var another: TypedB { get }
}

protocol B {
    associatedtype BModel
    func doAnother(anotherModel: BModel)
}

【问题讨论】:

标签: swift associated-types


【解决方案1】:

请找到以下工作游乐场示例。您需要使用关联类型的名称,而不是约束协议的名称。原因描述为here

import Foundation

protocol A {
    associatedtype AModel
    associatedtype TypedB: B where TypedB.BModel == AModel
    var another: TypedB { get }
}

protocol B {
    associatedtype BModel
    func doAnother(anotherModel: BModel)
}

// compiles

struct One: B {
    typealias BModel = String
    func doAnother(anotherModel: String) {}
}

struct Second: A {
    typealias AModel = String
    typealias TypedB = One
    var another: One
}

// does not compile

struct Third: B {
    typealias BModel = Int
    func doAnother(anotherModel: Int) {}
}

struct Fourth: A { // A' requires the types 'Fourth.AModel' (aka 'String') and 'Third.BModel' (aka 'Int') be equivalent
    typealias AModel = String
    typealias TypedB = Third
    var another: Third
}

【讨论】:

  • 这很好,直到我不得不创建一个 A 的实现。它迫使你用一个具体的实现来定义 TypedB :(
  • 那么请您详细说明您的问题?我没有得到你想要达到的目标。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 2019-08-24
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多