### Swift: Fluent Method and Function Naming Examples Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates how to name methods and functions in Swift to form grammatical English phrases for improved readability. This includes examples of direct insertion, filtering by properties, and transformations. ```swift x.insert(y, at: z) // "x, insert y at z" x.subviews(havingColor: y) // "x's subviews having color y" x.capitalizingNouns() // "x, capitalizing nouns" x.insert(y, position: z) x.subviews(color: y) x.nounCapitalize() AudioUnit.instantiate( with: description, options: [.inProcess], completionHandler: stopProgressBar ) ``` -------------------------------- ### Swift Initializers with Argument Labels for Narrowing Conversions Source: https://www.swift.org/documentation/api-design-guidelines/index Shows Swift initializer examples where argument labels are used for narrowing type conversions, like truncating or saturating a UInt64 to a UInt32. ```swift extension UInt32 { /// Creates an instance having the specified `value`. init("_": value: Int16) ← Widening, so no label /// Creates an instance having the lowest 32 bits of `source`. init("truncating" source: UInt64) /// Creates an instance having the nearest representable /// approximation of `valueToApproximate`. init("saturating" valueToApproximate: UInt64) } ``` -------------------------------- ### Swift API Documentation: Reverse Collection Source: https://www.swift.org/documentation/api-design-guidelines/index Example of documenting a Swift function that returns a reversed view of a collection. It uses a concise summary in Markdown format. ```swift /// **Returns a "view" of `self` containing the same elements in** /// **reverse order.** func reversed() -> ReverseCollection ``` -------------------------------- ### Swift Method Family Example (Less Preferred) Source: https://www.swift.org/documentation/api-design-guidelines/index Presents an alternative Swift API design using a family of methods with different signatures. This approach is generally less preferred than using defaulted parameters due to increased documentation burden and potential user confusion. ```swift extension String { /// _...description 1..._ public func **compare**(_ other: String) -> Ordering /// _...description 2..._ public func **compare**(_ other: String, options: CompareOptions) -> Ordering /// _...description 3..._ public func **compare**( _ other: String, options: CompareOptions, range: Range) -> Ordering /// _...description 4..._ public func **compare**( _ other: String, options: StringCompareOptions, range: Range, locale: Locale) -> Ordering } ``` -------------------------------- ### Swift: Method Naming for Clarity (Include Necessary Words) Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates how including specific words in method signatures, like 'at', prevents ambiguity. Omitting such words can lead to misinterpretation of the method's purpose, as shown in the 'remove(x)' example versus 'remove(at: x)'. ```swift extension List { public mutating func remove(at position: Index) -> Element } employees.remove(at: x) employees.remove(x) // unclear: are we removing x? ``` -------------------------------- ### Swift Function Signature with Named Parameters Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates how to use descriptive parameter names in Swift function signatures to enhance documentation readability. Clear names like 'start' and 'end' make the function's purpose immediately understandable. ```swift func move(from **start**: Point, to **end**: Point) ``` -------------------------------- ### Swift API Documentation: Subscript Access Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift subscript that describes what element is accessed by its index. It specifies the access type (get set). ```swift /// **Accesses** the `index`th element. subscript(index: Int) -> Element { get set } ``` -------------------------------- ### Swift: Method Naming to Omit Needless Words Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates the principle of omitting redundant words in API names. The example shows how 'removeElement(_:)' can be simplified to 'remove(_:)' when the 'Element' type is already implied by the context, making the API more concise. ```swift public mutating func removeElement(_ member: Element) -> Element? allViews.removeElement(cancelButton) public mutating func remove(_ member: Element) -> Element? allViews.remove(cancelButton) // clearer ``` -------------------------------- ### Divergent Method Semantics with Same Name in Swift Source: https://www.swift.org/documentation/api-design-guidelines/index Highlights a case where methods with the same name (`index`) have different semantics and should be named differently. The example shows `index()` for rebuilding a database index and `index(_:inTable:)` for retrieving a table row. ```swift extension Database { /// Rebuilds the database's search index func index() { ... } /// Returns the `n`th row in the given table. func index(_ n: Int, inTable: TableID) -> TableRow { ... } } ``` -------------------------------- ### Swift Function Calls Omitting First Argument Label for Grammatical Phrases Source: https://www.swift.org/documentation/api-design-guidelines/index Shows Swift examples where the first argument label is omitted because it forms part of a grammatical phrase, like adding a subview or dismissing a view controller. ```swift x.addSubview(y) view.dismiss("animated:": false) let text = words.split("maxSplits:": 12) let studentsByName = students.sorted("isOrderedBefore:": Student.namePrecedes) ``` -------------------------------- ### Swift: Array Append Overload Resolution Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates an ambiguity in Swift's `Array` `append` method overloads when dealing with unconstrained types like `Any`. The example shows how naming a parameter explicitly, like `contentsOf`, resolves the ambiguity. ```swift struct Array { /// Inserts `newElement` at `self.endIndex`. public mutating func append(_ newElement: Element) /// Inserts the contents of `newElements`, in order, at /// `self.endIndex`. public mutating func append(_ newElements: S) where S.Generator.Element == Element } var values: [Any] = [1, "a"] values.append([2, 3, 4]) // [1, "a", [2, 3, 4]] or [1, "a", 2, 3, 4]? struct Array { /// Inserts `newElement` at `self.endIndex`. public mutating func append(_ newElement: Element) /// Inserts the contents of `newElements`, in order, at /// `self.endIndex`. public mutating func append(**contentsOf** newElements: S) where S.Generator.Element == Element } ``` -------------------------------- ### Avoiding Ambiguity with Method Overloading in Swift Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates a scenario to avoid in Swift API design: overloading on return type, which can cause ambiguities with type inference. The example shows two `value` methods returning different optional types (`Int?` and `String?`) from the same `Box` type. ```swift extension Box { /// Returns the `Int` stored in `self`, if any, and /// `nil` otherwise. func value() -> Int? { ... } /// Returns the `String` stored in `self`, if any, and /// `nil` otherwise. func value() -> String? { ... } } ``` -------------------------------- ### Swift API Documentation: Initializer Creation Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift initializer that explains what instance it creates. It details the parameters used for creation. ```swift /// **Creates** an instance containing `n` repetitions of `x`. init(count n: Int, repeatedElement x: Element) ``` -------------------------------- ### Swift Naming Conventions: Case and Acronyms Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates Swift's naming conventions, specifically `UpperCamelCase` for types and protocols, and `lowerCamelCase` for everything else. It also shows how to handle acronyms and initialisms, either by conforming to case conventions or treating them as ordinary words. ```swift var utf8Bytes: [UTF8.CodeUnit] var isRepresentableAsASCII = true var userSMTPServer: SecureSMTPServer var radarDetector: RadarScanner var enjoysScubaDiving = true ``` -------------------------------- ### Swift: Initializer and Factory Method Argument Naming Source: https://www.swift.org/documentation/api-design-guidelines/index Shows how to name arguments for initializers and factory methods in Swift to avoid creating awkward or ungrammatical phrases when combined with the base name. ```swift let foreground = Color(red: 32, green: 64, blue: 128) let newPart = factory.makeWidget(gears: 42, spindles: 14) let ref = Link(target: destination) // Less fluent examples: let foreground = Color(havingRGBValuesRed: 32, green: 64, andBlue: 128) let newPart = factory.makeWidget(havingGearCount: 42, andSpindleCount: 14) let ref = Link(to: destination) // Value preserving type conversion exception: let rgbForeground = RGBColor(cmykForeground) ``` -------------------------------- ### Swift: Factory Method Naming Convention Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates the convention of prefixing factory method names with 'make' in Swift. This clarifies the intent of creating new instances or objects. ```swift x.makeIterator() ``` -------------------------------- ### Swift API Documentation: Prepending Element Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift mutating method that inserts an element at the beginning of a collection. The documentation focuses on the action and the input parameter. ```swift /// **Inserts** `newHead` at the beginning of `self`. mutating func prepend(_ newHead: Int) ``` -------------------------------- ### Swift API Documentation: Prepending List Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift function that returns a new list with an element prepended. It clearly states what the function returns. ```swift /// **Returns** a `List` containing `head` followed by the elements /// of `self`. func prepending(_ head: Element) -> List ``` -------------------------------- ### Swift API Documentation: Print Function Source: https://www.swift.org/documentation/api-design-guidelines/index Comprehensive documentation for a Swift print function, including a summary, extended discussion, parameter descriptions, and symbol commands like 'Note' and 'SeeAlso'. ```swift /// Writes the textual representation of each ← Summary /// element of `items` to the standard output. /// ← Blank line /// The textual representation for each item `x` ← Additional discussion /// is generated by the expression `String(x)`. /// /// - **Parameter separator**: text to be printed ⎫ /// between items. ⎟ /// - **Parameter terminator**: text to be printed ⎬ Parameters section /// at the end. ⎟ /// ⎭ /// - **Note**: To print without a trailing ⎫ /// newline, pass `terminator: ""` ⎟ /// ⎬ Symbol commands /// - **SeeAlso**: `CustomDebugStringConvertible`, /// `CustomStringConvertible`, `debugPrint`. ⎭ public func print( _ items: Any..., separator: String = " ", terminator: String = "\n") ``` -------------------------------- ### Swift Function Call with Argument Labels Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates the use of explicit argument labels in Swift function calls for clarity, especially when defining movement between points. ```swift func move("from" start: Point, "to" end: Point) x.move("from:": x, "to:": y) ``` -------------------------------- ### Swift: Protocol Naming Conventions Source: https://www.swift.org/documentation/api-design-guidelines/index Outlines Swift protocol naming conventions. Protocols describing 'what something is' should be nouns, while those describing capabilities should use 'able', 'ible', or 'ing' suffixes. ```swift // Describes 'what something is' protocol Collection { ... } // Describes a capability protocol Equatable { ... } protocol ProgressReporting { ... } ``` -------------------------------- ### Swift: Compensating for Weak Type Information in Parameters Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates how to enhance clarity for parameters with weak type information (e.g., NSObject, String, Int). Preceding such parameters with nouns describing their role, like 'Observer' and 'KeyPath', makes the call site unambiguous. ```swift func add(_ observer: NSObject, for keyPath: String) grid.add(self, for: graphics) // vague func addObserver(_ observer: NSObject, forKeyPath path: String) grid.addObserver(self, forKeyPath: graphics) // clear ``` -------------------------------- ### Swift: Naming Parameters and Associated Types by Role Source: https://www.swift.org/documentation/api-design-guidelines/index Explains how to name variables, parameters, and associated types based on their roles rather than just their type constraints. This improves clarity, especially when type names might be generic or repetitive, as seen with 'ViewType' vs 'ContentView'. ```swift var string = "Hello" protocol ViewController { associatedtype ViewType : View } class ProductionLine { func restock(from widgetFactory: WidgetFactory) } var greeting = "Hello" protocol ViewController { associatedtype ContentView : View } class ProductionLine { func restock(from supplier: WidgetFactory) } ``` -------------------------------- ### Free Functions in Swift API Design Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates scenarios where free functions are preferred over methods or properties in Swift API design. These include cases where there's no obvious `self`, for unconstrained generics, or when function syntax is part of established domain notation. ```swift min(x, y, z) print(x) sin(x) ``` -------------------------------- ### Swift API Documentation: List Struct Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift struct named 'List', describing its core functionality as a collection supporting efficient insertion/removal. It also documents a property 'first'. ```swift /// **A collection that** supports equally efficient insertion/removal /// at any position. struct List { /// **The element at the beginning** of `self`, or `nil` if self is /// empty. var first: Element? ... } ``` -------------------------------- ### Swift: Boolean Method/Property Usage Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates how boolean methods and properties in Swift should read as assertions about the receiver when used nonmutatingly. ```swift x.isEmpty line1.intersects(line2) ``` -------------------------------- ### Swift Function with Defaulted Parameters for Simplicity Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates how defaulted parameters in Swift can simplify function calls and improve readability. By providing default values for 'options', 'range', and 'locale', the common use case becomes much cleaner. ```swift extension String { /// _...description..._ public func compare( _ other: String, options: CompareOptions **= []**, range: Range? **= nil**, locale: Locale? **= nil** ) -> Ordering } ``` -------------------------------- ### Swift: Mutating vs. Nonmutating Method Naming Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates consistent naming for mutating and nonmutating method pairs in Swift. Mutating methods use imperative verbs, while nonmutating counterparts use 'ed' or 'ing' suffixes. ```swift // Using 'ed' suffix for nonmutating (past participle) mutating func reverse() { ... } func reversed() -> Self { ... } x.reverse() let y = x.reversed() // Using 'ing' suffix for nonmutating (present participle) mutating func stripNewlines() { ... } func strippingNewlines() -> String { ... } s.stripNewlines() let oneLine = t.strippingNewlines() // Using 'form' prefix for mutating (when noun is natural) x = y.union(z) // Nonmutating y.formUnion(z) // Mutating j = c.successor(i) // Nonmutating c.formSuccessor(&i) // Mutating ``` -------------------------------- ### Swift API Documentation: Pop First Element Source: https://www.swift.org/documentation/api-design-guidelines/index Documentation for a Swift mutating method that removes and returns the first element of a collection, handling the case where the collection is empty. The documentation notes the optional return value. ```swift /// **Removes and returns** the first element of `self` if non-empty; /// returns `nil` otherwise. mutating func popFirst() -> Element? ``` -------------------------------- ### Swift String Comparison with Defaulted Options Source: https://www.swift.org/documentation/api-design-guidelines/index Shows a simplified Swift string comparison call leveraging defaulted parameters. The parameters 'options', 'range', and 'locale' have default values, allowing for a more concise invocation when defaults are appropriate. ```swift let order = lastName.**compare(royalFamilyName)** ``` -------------------------------- ### Swift Function Calls with Modified Prepositional Phrase Labels Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates an exception in Swift API design where argument labels begin after the preposition to maintain abstraction clarity, like moving to specific X and Y coordinates or fading from a color. ```swift a.moveTo("x:": b, "y:": c) a.fadeFrom("red:": b, "green:": c, "blue:": d) ``` -------------------------------- ### Swift: Naming Functions/Methods by Side-Effects Source: https://www.swift.org/documentation/api-design-guidelines/index Explains Swift naming conventions for functions and methods based on whether they have side-effects. Non-mutating methods read as noun phrases, while mutating methods read as imperative verb phrases. ```swift // Without side-effects (noun phrases) x.distance(to: y) i.successor() // With side-effects (imperative verb phrases) print(x) x.sort() x.append(y) ``` -------------------------------- ### Swift Function with Predicate Parameter Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates using a well-named parameter 'predicate' for a closure in a Swift function. This naming convention makes the function's intent clear, improving documentation quality. ```swift /// Return an `Array` containing the elements of `self` /// that satisfy `**predicate**`. func filter(_ **predicate**: (Element) -> Bool) -> [Generator.Element] ``` -------------------------------- ### Swift: Type, Property, Variable, and Constant Naming Source: https://www.swift.org/documentation/api-design-guidelines/index Specifies that other types, properties, variables, and constants in Swift should be named as nouns to clearly indicate their nature. ```swift let count: Int var name: String struct User { ... } ``` -------------------------------- ### Swift Initializer Omitting First Argument Label Source: https://www.swift.org/documentation/api-design-guidelines/index Illustrates how to omit the first argument label in Swift initializers that perform value-preserving type conversions, such as converting a BigInt to a String. ```swift extension String { // Convert `x` into its textual representation in the given radix init("_": x: BigInt, radix: Int = 10) ← Note the initial underscore } text = "The value is: " text += String(veryLargeNumber) text += " and in hexadecimal, it's" text += String(veryLargeNumber, radix: 16) ``` -------------------------------- ### Swift Function Calls with Prepositional Phrase Argument Labels Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates Swift API design where argument labels are part of a prepositional phrase, such as removing boxes having a certain length or fading with specific color components. ```swift x.removeBoxes(havingLength: 12) a.move("toX:": b, "y:": c) a.fade("fromRed:": b, "green:": c, "blue:": d) ``` -------------------------------- ### Swift Function for Replacing Range with New Elements Source: https://www.swift.org/documentation/api-design-guidelines/index Shows a Swift function signature where parameter names 'subRange' and 'newElements' clearly describe their roles. This improves the clarity of documentation and code usage. ```swift /// Replace the given `**subRange**` of elements with `**newElements**`. mutating func replaceRange(_ **subRange**: Range, with **newElements**: [E]) ``` -------------------------------- ### Swift: Ensure Unique Storage Function Source: https://www.swift.org/documentation/api-design-guidelines/index Demonstrates a Swift mutating function `ensureUniqueStorage` that ensures sufficient capacity for storage. It takes a minimum capacity and an allocation closure, returning booleans indicating if reallocation or capacity change occurred. The closure parameter `byteCount` is highlighted. ```swift /// Ensure that we hold uniquely-referenced storage for at least /// `requestedCapacity` elements. /// /// If more storage is needed, `allocate` is called with /// **`byteCount`** equal to the number of maximally-aligned /// bytes to allocate. /// /// - Returns: /// - **reallocated**: `true` if a new block of memory /// was allocated; otherwise, `false`. /// - **capacityChanged**: `true` if `capacity` was updated; /// otherwise, `false`. mutating func ensureUniqueStorage( minimumCapacity requestedCapacity: Int, allocate: (_ **byteCount**: Int) -> UnsafePointer ) -> (**reallocated:** Bool, **capacityChanged:** Bool) ``` -------------------------------- ### Method Overloading with Same Base Name in Swift Source: https://www.swift.org/documentation/api-design-guidelines/index Shows how methods can share a base name in Swift when they have the same basic meaning or operate in distinct domains. This is exemplified with `contains` methods operating on different types like `Point`, `Shape`, and `LineSegment`, as well as a `contains` method for `Collection` elements. ```swift extension Shape { /// Returns `true` if `other` is within the area of `self`; /// otherwise, `false`. func contains(_ other: Point) -> Bool { ... } /// Returns `true` if `other` is entirely within the area of `self`; /// otherwise, `false`. func contains(_ other: Shape) -> Bool { ... } /// Returns `true` if `other` is within the area of `self`; /// otherwise, `false`. func contains(_ other: LineSegment) -> Bool { ... } } extension Collection where Element : Equatable { /// Returns `true` if `self` contains an element equal to /// `sought`; otherwise, `false`. func contains(_ sought: Element) -> Bool { ... } } ``` -------------------------------- ### Swift Function Calls with Labeled Arguments for Default Values Source: https://www.swift.org/documentation/api-design-guidelines/index Highlights Swift's requirement to always label arguments with default values, even if they are omitted in the call, to maintain clarity and correct meaning. ```swift view.dismiss("animated:": false) let text = words.split("maxSplits:": 12) let studentsByName = students.sorted("isOrderedBefore:": Student.namePrecedes) ``` -------------------------------- ### Swift: Naming Associated Types with Protocol Suffix Source: https://www.swift.org/documentation/api-design-guidelines/index Addresses naming collisions when an associated type's role is identical to its protocol constraint. Appending 'Protocol' to the protocol name, as in 'IteratorProtocol', resolves this conflict while maintaining clarity. ```swift protocol Sequence { associatedtype Iterator : IteratorProtocol } protocol IteratorProtocol { ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.