有没有针对具有空初始化程序的Swift类/结构的标准协议

huangapple go评论50阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 07:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定