Swift 3 个函数命名规则

Swift 3 functions naming convention

我对 Swift 3

中的函数命名约定有点困惑

我仔细阅读了 Swift 3 条指南,发现方法命名约定应如下所示:

func move(from start: Point, to end: Point)
x.move(from: x, to: y)

但是...

如果我查看 UINavigationController 方法,我发现 pushViewControllerpresentViewController 方法。方法调用如下所示:

navigationController?.pushViewController(viewController, animated: true)
navigationController?.present(controller, animated: true)

我想知道为什么 pushViewController 方法调用不像 Swift3。以及为什么这两种方法之间存在不一致。根据指南,我认为 push 方法应该如下所示:

rootNavigationController?.push(viewController, animated: true)

那就更Swift3个赞了

让我们考虑一个简单的例子:

//1
func saveName(_ name : String) {}
saveName("John")

//2
func save(_ name: String){}
save("John")

//3
func save(name: String){}
save(name: "John")

在我看来,选项 3 最符合 Swift 3 准则。 但另一方面,由于我使用 pushViewControllerpresent(controller) 方法的示例,选项编号 1 也很好。

所以我的问题是:

哪个是最符合 Swift 3 条准则的最佳选择?

更新

由于@Sweeper 的回答,它解决了为什么 pushpresent 方法之间存在不一致的问题。

来源:

https://github.com/raywenderlich/swift-style-guide

https://swift.org/documentation/api-design-guidelines/#parameter-names

请看这里:https://github.com/apple/swift-evolution/blob/master/proposals/0005-objective-c-name-translation.md

上面写着:

- Never prune a suffix from the base name of a method that matches a property of the enclosing class:

This heuristic has the effect of preventing us from producing too-generic names for methods that conceptually modify a property of the class.

... If we were to drop GestureRecognizer, leaving just add, we end up with a method that conceptually modifies the gestureRecognizers property but uses an overly generic name to do so:

这就是 pushViewController 未重命名的原因。在UINavigationController中,有一个属性叫做viewControllers。为了避免“过于通用的名称”。

为什么 present 改名了?

注意 present 是在 UIViewController 中定义的。 UIViewController 没有名为 viewControllerviewControllers 的 属性,因此 ViewController 部分被删减。

不一致:

  • 许多 UIKitFoundation 框架已在 Objective-C 中构建,并且在 Swift 之前就已存在。
  • 所以他们有一个 Swift 接口来访问它们,大多数地方他们都试图匹配它,是的,有时会有不一致。

目标:

具有或不具有外部参数名称的函数都是完全可以的。这取决于场景(class、功能和上下文)

目标是定义函数名称,使函数名称(不带参数)单独描述函数将执行的操作。

从用法和调用方式来看。清晰的名称确实可以提高可读性并为良好的设计铺平道路(避免混淆函数在 class A 或 class B

中的位置

示例:

struct Record {
    
    var name : String
    var age : Int
    
    func save() {}
}
  • 在这种情况下,完全没有任何参数可能是有意义的,因为 nameageRecord[=23= 中的属性]

  • 所以class / struct / enum 也添加了上下文,所以可以避免不必要/多余的词。

  • 有副作用的函数用动词表示

  • 没有副作用的函数用名词表示

  • 参考下面的link变异和非变异函数。

答案:

所以这取决于上下文并尝试查看 API 的用法,这将提供更多见解,您可以如何设计 API。

record.save()

注意:以上只是一个例子,可能在你的场景中save函数可能是不同上下文的一部分。

参考:

https://swift.org/documentation/api-design-guidelines/