gpt4 book ai didi

swift - Swift 中改变函数的命名约定

转载 作者:IT王子 更新时间:2023-10-29 05:43:10 25 4
gpt4 key购买 nike

在 Ruby 中,变异方法(即修改 self 的方法)按照惯例用感叹号 (!) 标记,以将它们与不修改 self 的类似命名方法分开。

例如 Array#sort 返回一个排序的数组,但是 Array#sort! 修改调用它的数组。

我现在开始研究 Swift。我如何命名变异方法以将其与其非变异孪生方法分开?

我知道 Python 有 sorted(list)list.sort()。这是一个值得遵循的好模式吗,即 .sorted()(非变异)和 .sort()(变异)?

那些不容易以这种方式转换的名称怎么样,例如 String#nextString#next!

最佳答案

关于发布官方指南,这里是: https://swift.org/documentation/api-design-guidelines/#name-according-to-side-effects

Name Mutating/nonmutating method pairs consistently. A mutating method will often have a nonmutating variant with similar semantics, but that returns a new value rather than updating an instance in-place.

  • When the operation is naturally described by a verb, use the verb’s imperative for the mutating method and apply the “ed” or “ing” suffix to name its nonmutating counterpart.

    Mutating    Nonmutating
    x.sort() z = x.sorted()
    x.append(y) z = x.appending(y)

    Prefer to name the nonmutating variant using the verb’s past participle (usually appending “ed”):

    /// Reverses `self` in-place.
    mutating func reverse()

    /// Returns a reversed copy of `self`.
    func reversed() -> Self
    ...
    x.reverse()
    let y = x.reversed()

    When adding “ed” is not grammatical because the verb has a direct object, name the nonmutating variant using the verb’s present participle, by appending “ing.”

    /// Strips all the newlines from `self`
    mutating func stripNewlines()

    /// Returns a copy of `self` with all the newlines stripped.
    func strippingNewlines() -> String
    ...
    s.stripNewlines()
    let oneLine = t.strippingNewlines()
  • When the operation is naturally described by a noun, use the noun for the nonmutating method and apply the “form” prefix to name its mutating counterpart.

    Nonmutating         Mutating
    x = y.union(z) y.formUnion(z)
    j = c.successor(i) c.formSuccessor(&i)

Ray Wenderlich自己总结一下 Swift Style Guide :

verb methods follow the -ed, -ing rule for the non-mutating version
noun methods follow the formX rule for the non-mutating version

请注意,由于提案:SE-0059 by Dave Abrahams,官方指南已针对 Swift 3 进行了更新。 , Update API Naming Guidelines and Rewrite Set APIs Accordingly , 2016 年 4 月 18 日批准后。

但五天前,即 2016 年 4 月 13 日,Erica Sadun在她的文章中表达了一些不同的观点Stop the Madness and fix the Swift API guidelines .让我们补充一下,Erica 之前就此事写过她自己的文章,Naming Methods and Functions ,也可以在她的书 Swift Style 中找到。为了好玩,她试图explain mutating naming with emoji .

关于swift - Swift 中改变函数的命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35484227/

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