Swift Naming Conventions

In Ruby, mutating methods (i.e. methods that modify self), by convention, marked bang (!), Separate them from similar methods that do not change self.

For example, it Array#sortreturns a sorted array, but Array#sort!changes the array on which it is called.

Now I began to study Swift. How can I name a mutating method to separate it from its non-mutating double?

I know that Python has sorted(list)vs list.sort(). Is this a good template i.e. .sorted()(not mutating) and .sort()(mutating)?

What about names that are not easily transformed in a way like String#nextvs String#next!?

+4
source share
1 answer

About the publication of official manuals, here they are: https://swift.org/documentation/api-design-guidelines/#name-according-to-side-effects

Mutating / nonmutating method parameter . A mutating method will often have a mutation-free option with similar semantics, but it returns a new value, rather than updating the instance in place.

  • When an operation is naturally described by a verb , use the verbs necessary for the mutation method and use the suffix "ed" or "ing" to name its unscaled copy.

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

    Prefer to name the non-mutating version using the verbs that have passed after participle (usually add "ed"):

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

    "ed" , , , participle, "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()
    
  • , , nonmutating "", .

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

Ray Wenderlich Swift Style Guide:

-ed, -ing -
formX

, Swift 3 : SE-0059 , API API API , 18 2016 .

, 13 2016 , Swift API. , , " " , Swift Style. emoji.

+2

Source: https://habr.com/ru/post/1629388/


All Articles