gpt4 book ai didi

swift - 在另一个协议(protocol)中重用协议(protocol)中的关联类型

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:57 25 4
gpt4 key购买 nike

这是我的代码:

protocol Requester {
associatedtype requestType

var response: ((requestType) -> ())? { get set }
}

protocol RequestProcesser: AnyObject {
// Is it possible to define a associated type that is equal to the associated type of Requester?
associatedtype requester: Requester

// This associatedtype should always be equal to Requester.requestType
associatedtype requestType

var request: requester { get set }
}

extension RequestProcesser {
func process() {
request.response = { response in

// Now I need to cast...
// Is there any way around this?
// the type of the response should be equal to requestType so the cast can be omitted right?
let x = response as! requestType
}
}
}

正如您在代码中的注释中看到的那样,我想知道我是否可以约束关联类型,使其与另一个协议(protocol)中的其他关联类型相等。目标是省略类型转换。现在,实现类可以为 requestType 选择不同的类型,这将导致崩溃。

最佳答案

requestType RequestProcessor 中不需要关联类型协议(protocol),因为它是基于 requester 的隐式协议(protocol)关联类型。

您应该能够定义 RequestProcessor像这样的协议(protocol):

protocol RequestProcesser: AnyObject {
associatedtype requester: Requester
var request: requester { get set }
}

然后像这样使用它:

class MyRequester: Requester {
typealias requestType = Int
var response: ((Int) -> ())?
}

class MyRequestProcessor: RequestProcesser {
typealias requester = MyRequester
var request = MyRequester()
}

现在,response process() 中的闭包参数方法将采用 MyRequester 的关联类型协议(protocol)(在本例中为 Int ),因此无需转换。

关于swift - 在另一个协议(protocol)中重用协议(protocol)中的关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53350930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com