gpt4 book ai didi

swift - Swift 方法中的第一个参数标签

转载 作者:搜寻专家 更新时间:2023-11-01 07:13:44 24 4
gpt4 key购买 nike

以下哪一种方法遵循 Swift 思想?

  • func addChapter(_ chapter: Chapter)
  • func add(chapter chapter: Chapter)
  • func add(_ chapter: Chapter)

最佳答案

TLDR:

根据 chapter 信息是否重要以区别于其他方法/含义,您应该使用第一个或第三个选项。不是第二个选项。

Include all the words needed to avoid ambiguity for a person reading code where the name is used.

..., if the first argument forms part of a grammatical phrase, omit its label, appending any preceding words to the base name, e.g. x.addSubview(y)

(来自 API Design Guidelines)


在不知道类的情况下,这不是那么容易决定的。

让我们考虑这是一个类:

class Book {
var chapters: [Chapter]
var pages: [Page]
var metadata: [MetaData]
}

如果你查看 Swift Evolution 0005关于导入 Obj-C 方法的方式,您可以了解到导入方法 [UIView addGestureRecognizer:] 的首选方式是 addGestureRecognizer(_:UIGestureRecognizer)

注意理由:

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.

所以有规则

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

您的第一个选择就是正确的解决方案。

另一方面,如果您的类具有以下形式:

class Chapters {
private var chapters: [Chapter]
}

(例如,类似数组的容器)

那么 add(_:) 就是正确的解决方案。

永远不要使用第二个选项 add(chapter:)

关于swift - Swift 方法中的第一个参数标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com