有没有办法在函数指针中设置协议的数据类型? [英] Is there a way to set the data type of the protocol in function pointer?

查看:47
本文介绍了有没有办法在函数指针中设置协议的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在swift中的函数指针中设置协议的数据类型?

Is there a way to set the data type of the protocol in function pointer in swift?

这是我的协议 ICRUDOOperation

public protocol ICRUDOperation {
    associatedtype T
    func insert(data:T)
    func update(data:T)
    func get(data:T) -> [T]
    func getList(data: BaseModel) -> [T]
    func getPage(data: BaseModel) -> [T]
    func delete(data: T)
}

我尝试使用的内容:

func delegate1<W>(sqlite: W, service: W, data: W.T) where W: ICRUDOperation {
    sqlite.insert(data: data)
}
var decision = [String : [String:((ICRUDOperation, ICRUDOperation, T) ->())?]]()

func fillDecision() {
    decision["Person"]?["1"] = Delegate1
}

我在决定中犯了这个错误

I get this error in decision

Protocol 'ICRUDOperation' can only be used as a generic constraint because it has Self or associated type requirements

fillDecision() 的错误:

Cannot assign value of type '(_, _, _.T) -> ()' to type '((ICRUDOperation, ICRUDOperation, _) -> ())??'

推荐答案

一旦您添加了关联类型,就不再有ICRUDOOperation"之类的东西.PAT(具有关联类型的协议)没有存在形式;它的存在是为了将方法附加到其他类型,或者限制哪些具体类型可以传递给泛型函数.您不能将 PAT 存储在变量、字典或其他任何地方.协议(以及双重的 PAT)不是抽象类.

Once you've added an associated type, there is no longer any such thing as a "ICRUDOperation". A PAT (protocol with associated type) has no existential form; it exists in order to attach methods to other types, or to restrict what concrete types may be passed to a generic function. You cannot store a PAT in a variable or dictionary or anywhere else. A protocol (and doubly-so a PAT) is not an abstract class.

要理解的最关键的事情是关联类型是由实现选择的,而不是由调用者选择的.因此,在您的示例中, T 将由 ICRUDOperation 的实现选择(与 Array 选择其 Collection.Index 为 Int 的方式相同;您无法选择它).泛型允许调用者选择类型,这看起来更像你想要实现的目标.

The most critical thing to understand is that associated types are selected by the implementation, not by the caller. So in your example, T would be selected by the implementation of ICRUDOperation (in the same way that Array chooses its Collection.Index to be Int; you don't get to pick that). Generics allow the caller to select the type, which looks more like what you're trying to achieve.

您如何解决此问题取决于您的用例,从您的示例中很难理解这一点.决策的目标是什么?

How you resolve this depends on your use case, which is difficult to understand from your example. What is the goal of decision?

如果您能展示您期望的 ICRUDOperation 的两个或三个不同实现的样子,那将会很有帮助.我不确定您打算操作的实现"是什么意思.

It would be helpful if you would demonstrate what you expect two or three different implementations of ICRUDOperation would look like. I'm not sure what you intend "an implementation of an operation" to mean.

这篇关于有没有办法在函数指针中设置协议的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆