英文:
Is there a standard protocol for Swift class/struct with an empty initializer
问题
I'm curious, is there a pre-existing protocol whose only requirement is that there be an init
with no arguments? I'm creating a generic that needs to be able to initialize an associated type without worrying about any arguments. This seems to call for a protocol like this:
protocol HasEmptyInitializer {
init()
}
It seems like a pretty basic protocol that might be needed in many contexts. Before I go polluting my protocol space with the above, I was wondering if there is anything like that already in Foundation or other 1st party library. Does anyone know of such a thing?
英文:
I'm curious, is there a pre-existing protocol whose only requirement is that there be an init
with no arguments? I'm creating a generic that needs to be able to initialize an associated type without worrying about any arguments. This seems to call for a protocol like this:
protocol HasEmptyInitializer {
init()
}
It seems like a pretty basic protocol that might be needed in many contexts. Before I go polluting my protocol space with the above, I was wondering if there is anything like that already in Foundation or other 1st party library. Does anyone know of such a thing?
答案1
得分: 1
这是一个非常著名的非协议,因为它缺乏语义。关于为什么这故意不是Swift协议的背景,请参阅Ole Begemann的文章协议不仅仅是语法的堆砌。如果你有一个具有语义意义的协议,只有这个要求,那么创建它就没有问题,但这相当罕见。
Ole的文章的基本观点(整合了许多其他对话)是,协议不仅仅是“它有这个方法”(即语法)。它涉及它促进了哪种算法。 "Plusable" 不是一个好的协议来涵盖“可以应用+的事物”。对于Ints来说,+ 的意思不同于对于Collections的+ 的意思(后者甚至不是可交换的)。类似地,“通过调用init()可创建”告诉你有关生成对象的含义。它是“空的”吗?一些未指定的“默认”值?无效?协议的语义比语法更重要。
英文:
This is a very famous non-protocol because it lacks semantics. For the background on why this is intentionally not a protocol in Swift, see Ole Begemann's writeup Protocols are more than Bags of Syntax. If you have a semantically meaningful protocol that only has this requirement, then there is no problem creating it, but it is quite rare.
The fundamental point of Ole's writeup (which gathers together many other conversations) is that a protocol is more than just "it has this method" (i.e. syntax). It's about what kinds of algorithms it facilitates. "Plusable" wouldn't be a good protocol to cover "things you can apply + to." What + means for Ints is not really the same as what + means for Collections (the latter isn't even commutative). Similarly, "makable by calling init()" tells you nothing about what the resulting object means. Is is "empty?" Some unspecified "default" value? Invalid? The semantics of protocols matter more than the syntax.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论