Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift关联类型约束_Swift_Associated Types - Fatal编程技术网

Swift关联类型约束

Swift关联类型约束,swift,associated-types,Swift,Associated Types,我有两个协议,每个协议定义一个关联的类型。其中一个协议需要定义另一个协议的类型化变量,其中两个协议的关联类型具有相同的类型。是否可能以某种方式推断关联类型的类型 protocol A { associatedtype AModel var b: B { get } } protocol B { associatedtype BModel func doAnother(anotherModel: BModel) } 这就是我尝试过但没有成功的方法 protoco

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

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

请查找以下工作操场示例。您需要使用关联类型的名称,而不是约束协议的名称。对此原因进行了描述


这是因为协议Superfighter{}其中一个协议没有关联的类型在我创建了A的实现之前,这非常棒。它迫使您使用具体的实现来定义TypedB:那么请您精确地回答您的问题好吗?我没有得到你想要的。
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
}