【问题标题】:Methods of parameterized types can omit type parameters参数化类型的方法可以省略类型参数
【发布时间】:2017-03-26 04:36:30
【问题描述】:

我在https://github.com/github/swift-style-guide/blob/master/README.md阅读了以下建议

但这部分我不明白。接收类型是什么,接收器是什么? 谢谢。

尽可能省略类型参数

参数化类型的方法可以省略类型参数 接收类型与接收者相同时。例如:

struct Composite<T> {
  …
  func compose(other: Composite<T>) -> Composite<T> {
      return Composite<T>(self, other)
  }
} 

可以呈现为:

struct Composite<T> {
  …
  func compose(other: Composite) -> Composite {
      return Composite(self, other)
  }
}

【问题讨论】:

标签: swift generics


【解决方案1】:

“类型参数”是指泛型结构的具体类型。例如,您可以有一个 Composite&lt;Int&gt; 类型的结构 A。类型参数为Int。像T 这样的类型参数是一个泛型类型参数,它可以代表任何类型的具体类型,除非受到约束。

样式指南使用 Swift 编译器非常擅长推断类型参数这一事实,因此您可以直接编写 Composite 而不使用类型参数。如果在本例中,Composite 的初始值设定项指定两个参数必须是同一类型,则可以执行此操作。既然 Swift 知道selfComposite&lt;T&gt; 类型,那么它知道other 也必须是Composite&lt;T&gt; 类型,并且由于Composite.init(::) 返回一个相同类型的结构,那么返回类型是@987654332 @。当然,这一切都取决于初始化程序。

就我个人而言,在这一点上我不同意风格指南。明确一点总是更好,尖括号不会占用太多空间。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2016-12-08
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多