返回 Skills
erikote04/swift-api-design-guidelines-agent-skill· MIT 内容可用

swift-api-design-guidelines-skill

Write, review, or improve Swift APIs using Swift API Design Guidelines for naming, argument labels, documentation comments, terminology, and general conventions. Use when designing new APIs, refactoring existing interfaces, or reviewing API clarity and fluency.

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: swift-api-design-guidelines-skill description: Write, review, or improve Swift APIs using Swift API Design Guidelines for naming, argument labels, documentation comments, terminology, and general conventions. Use when designing new APIs, refactoring existing interfaces, or reviewing API clarity and fluency.

Swift API Design Guidelines Skill

Overview

Use this skill to design and review Swift APIs that are clear at the point of use, fluent in call sites, and aligned with established Swift naming and labeling conventions. Prioritize readability, explicit intent, and consistency across declarations, call sites, and documentation comments.

Work Decision Tree

1) Review existing code

  • Inspect declarations and call sites together, not declarations alone.
  • Check naming clarity and fluency (see references/promote-clear-usage.md, references/strive-for-fluent-usage.md).
  • Check argument labels and parameter naming (see references/parameters.md, references/argument-labels.md).
  • Check documentation comments and symbol markup (see references/fundamentals.md).
  • Check conventions and overload safety (see references/general-conventions.md, references/special-instructions.md).

2) Improve existing code

  • Rename APIs that are ambiguous, redundant, or role-unclear.
  • Refactor labels to improve grammatical call-site reading.
  • Replace weakly named parameters with role-based names.
  • Resolve overload sets that become ambiguous with weak typing.
  • Strengthen documentation summaries to describe behavior and returns precisely.

3) Implement new feature

  • Start from use-site examples before finalizing declarations.
  • Choose base names and labels so calls read as clear English phrases.
  • Add defaults only when they simplify common usage.
  • Define mutating/nonmutating pairs with consistent naming.
  • Add concise documentation comments for every new declaration.

Core Guidelines

Fundamentals

  • Clarity at the point of use is the top priority.
  • Clarity is more important than brevity.
  • Every declaration should have a documentation comment.
  • Summaries should state what the declaration does, returns, accesses, creates, or is.
  • Use recognized Swift symbol markup (Parameter, Returns, Throws, Note, etc.).

Promote Clear Usage

  • Include all words needed to avoid ambiguity.
  • Omit needless words, especially type repetition.
  • Name parameters and associated types by role, not type.
  • Add role nouns when type information is weak (Any, NSObject, String, Int).

Strive For Fluent Usage

  • Prefer method names that produce grammatical, readable call sites.
  • Start factory methods with make.
  • Name side-effect-free APIs as noun phrases; side-effecting APIs as imperative verbs.
  • Keep mutating/nonmutating naming pairs consistent (sort/sorted, formUnion/union).
  • Boolean APIs should read as assertions (isEmpty, intersects).

Use Terminology Well

  • Prefer common words unless terms of art are necessary for precision.
  • If using a term of art, preserve its established meaning.
  • Avoid non-standard abbreviations.
  • Embrace established domain precedent when it improves shared understanding.

Conventions, Parameters, And Labels

  • Document complexity for computed properties that are not O(1).
  • Prefer methods/properties to free functions except special cases.
  • Follow Swift casing conventions, including acronym handling.
  • Use parameter names that improve generated documentation readability.
  • Prefer default arguments over method families when semantics are shared.
  • Place defaulted parameters near the end.
  • Apply argument labels based on grammar and meaning, not style preference.

Special Instructions

  • Label tuple members and name closure parameters in public API surfaces.
  • Be explicit with unconstrained polymorphism to avoid overload ambiguity.
  • Align names with semantics shown in documentation comments.

Quick Reference

Name Shape

SituationPreferred Pattern
Mutating verbreverse()
Nonmutating verbreversed() / strippingNewlines()
Nonmutating noun opunion(_:)
Mutating noun opformUnion(_:)
Factory methodmakeWidget(...)
Boolean queryisEmpty, intersects(_:)

Argument Label Rules

SituationRule
Distinguishable unlabeled argsOmit labels only if distinction is still clear
Value-preserving conversion initOmit first label
First arg in prepositional phraseUsually label from the preposition
First arg in grammatical phraseOmit first label
Defaulted argumentsKeep labels (they may be omitted at call sites)
All other argumentsLabel them

Documentation Rules

Declaration KindSummary Should Describe
Function / methodWhat it does and what it returns
SubscriptWhat it accesses
InitializerWhat it creates
Other declarationsWhat it is

Review Checklist

Clarity And Fluency

  • Call sites are clear without reading implementation details.
  • Base names include all words needed to remove ambiguity.
  • Names are concise and avoid repeating type names.
  • Calls read naturally and grammatically where it matters most.

Naming Semantics

  • Side-effect-free APIs read as nouns/queries.
  • Side-effecting APIs read as imperative verbs.
  • Mutating/nonmutating pairs use consistent naming patterns.
  • Boolean APIs read as assertions.

Parameters And Labels

  • Parameter names improve docs and role clarity.
  • Default parameters simplify common usage.
  • Defaulted parameters are near the end.
  • First argument labels follow grammar and conversion rules.
  • Remaining arguments are labeled unless omission is clearly justified.

Documentation And Conventions

  • Every declaration has a useful summary comment.
  • Symbol markup is used where appropriate.
  • Non-O(1) computed property complexity is documented.
  • Case conventions and acronym casing follow Swift norms.
  • Overloads avoid return-type-only distinctions and weak-type ambiguities.

References

  • references/fundamentals.md - Core principles and documentation comment rules
  • references/promote-clear-usage.md - Ambiguity reduction and role-based naming
  • references/strive-for-fluent-usage.md - Fluency, side effects, and mutating pairs
  • references/use-terminology-well.md - Terms of art, abbreviations, and precedent
  • references/general-conventions.md - Complexity docs, free function exceptions, casing, overloads
  • references/parameters.md - Parameter naming and default argument strategy
  • references/argument-labels.md - First-argument and general label rules
  • references/special-instructions.md - Tuple/closure naming and unconstrained polymorphism

Philosophy

  • Prefer clear use-site semantics over declaration cleverness.
  • Follow established Swift conventions before inventing local style rules.
  • Optimize for maintainability and reviewability of public API surfaces.
  • Keep guidance practical: apply the smallest change that improves clarity.

附带文件

references/argument-labels.md
# Argument Labels

## Omit Labels Only When It Is Still Clear
- Omit all labels only when unlabeled arguments cannot be usefully distinguished.

Examples:
- `min(x, y)`
- `zip(a, b)`

## Value-Preserving Conversion Initializers
- Omit the first argument label for value-preserving conversions.
- The first argument should be the conversion source.

```swift
let value = Int64(someUInt32)
```

## Prepositional Phrase Rule
- If the first argument is part of a prepositional phrase, usually include the label beginning with the preposition.

```swift
x.removeBoxes(havingLength: 12)
```

Exception:
- When first arguments are parts of one abstraction, move the label boundary after the preposition.

```swift
a.moveTo(x: b, y: c)
a.fadeFrom(red: b, green: c, blue: d)
```

## Grammatical Phrase Rule
- If the first argument forms part of a grammatical phrase, omit its label and move leading words into the base name.

```swift
x.addSubview(y)
```

## Label Everything Else
- If the first argument is not part of a grammatical phrase, label it.
- Label all remaining arguments unless a specific rule justifies omission.

```swift
view.dismiss(animated: false)
words.split(maxSplits: 12)
students.sorted(isOrderedBefore: Student.namePrecedes)
```
references/fundamentals.md
# Fundamentals

## Core Priorities
- Clarity at the point of use is the most important design goal.
- Clarity is more important than brevity.
- Evaluate declarations in real call-site context, not in isolation.

## Documentation Is Part Of API Design
- Write a documentation comment for every declaration.
- If the API is hard to describe simply, redesign may be needed.
- Use Swift Markdown and recognized symbol markup.

## Summary Writing Rules
- Start with a summary that can stand on its own.
- Prefer a single sentence fragment ending in a period.
- Describe:
  - Functions/methods: what they do and return.
  - Subscripts: what they access.
  - Initializers: what they create.
  - Other declarations: what they are.

## Suggested Structure
```swift
/// Returns a "view" of `self` containing the same elements in
/// reverse order.
func reversed() -> ReverseCollection
```

```swift
/// Accesses the `index`th element.
subscript(index: Int) -> Element { get set }
```

```swift
/// Creates an instance containing `n` repetitions of `x`.
init(count n: Int, repeatedElement x: Element)
```

## Additional Comment Content
- Add extra paragraphs only when they improve comprehension.
- Use symbol markup bullets when relevant, such as:
  - `Parameter` / `Parameters`
  - `Returns`
  - `Throws`
  - `Note`
  - `Warning`
  - `SeeAlso`

## Practical Check
- Read a use-site snippet and confirm the intent is obvious without external explanation.
references/general-conventions.md
# General Conventions

## Document Computed Property Complexity
- If a computed property is not `O(1)`, document its complexity.
- Many readers assume property access is cheap unless told otherwise.

## Prefer Methods/Properties To Free Functions
Use free functions only when:
1. There is no obvious `self`.
2. The function is an unconstrained generic.
3. Function syntax is established domain notation.

## Follow Swift Casing
- Types/protocols: `UpperCamelCase`.
- Other declarations: `lowerCamelCase`.
- Acronyms and initialisms should be cased consistently with style conventions.

```swift
var utf8Bytes: [UTF8.CodeUnit]
var isRepresentableAsASCII = true
var radarDetector: RadarScanner
```

## Overloads
- Methods may share base names when meaning is the same or domains are distinct.
- Do not reuse a base name for semantically different operations.
- Avoid overloading on return type alone; type inference can make calls ambiguous.

## Review Heuristic
- Check that overload sets are readable, semantically coherent, and unambiguous at call sites.
references/parameters.md
# Parameters

## Choose Names For Documentation Quality
- Parameter names do not appear at most call sites, but they drive documentation clarity.
- Select names that read naturally in summaries and parameter descriptions.

```swift
/// Returns the elements of `self` that satisfy `predicate`.
func filter(_ predicate: (Element) -> Bool) -> [Element]
```

## Prefer Defaults For Common Cases
- Use default values when one value is commonly used.
- Defaults reduce noise in common call sites and improve readability.

```swift
lastName.compare(royalFamilyName)
```

## Prefer A Single API With Defaults Over Method Families
- Multiple overloads with mostly shared semantics increase cognitive load.
- One method with defaults is usually easier to learn and maintain.

## Place Defaulted Parameters Near The End
- Non-defaulted parameters typically carry core semantics.
- Keep the call pattern stable and predictable.

## `#fileID`, `#filePath`, `#file`
- Prefer `#fileID` for production APIs to save space and avoid exposing full paths.
- Use `#filePath` where full paths are intentionally useful (e.g., tests/tools).
- Use `#file` for Swift 5.2-and-earlier compatibility needs.
references/promote-clear-usage.md
# Promote Clear Usage

## Include Words Needed For Clarity
- Keep all words required to avoid ambiguity at the call site.
- Do not remove words that carry semantic distinction.

```swift
employees.remove(at: index)   // clear position-based removal
employees.remove(index)       // ambiguous
```

## Omit Needless Words
- Remove words that repeat type information and add no meaning.
- Prefer role-focused words over type-focused words.

```swift
allViews.remove(cancelButton)         // preferred
allViews.removeElement(cancelButton)  // redundant
```

## Name By Role, Not Type
- Variables, parameters, and associated types should describe role.
- Avoid reusing type names as identifiers when a role name is better.

```swift
var greeting = "Hello"
func restock(from supplier: WidgetFactory)
associatedtype ContentView: View
```

## Compensate For Weak Type Information
- Weakly typed values (`Any`, `NSObject`, primitives) often need extra role words.
- Add role nouns to disambiguate intent.

```swift
func addObserver(_ observer: NSObject, forKeyPath path: String)
```

## Review Heuristic
- Ask: "Can a reader infer semantics from call-site text alone?"
- If not, add the smallest amount of naming context needed.
references/special-instructions.md
# Special Instructions

## Tuple And Closure Naming
- Label tuple members in API signatures.
- Name closure parameters where they appear in the API.
- These names improve call-site readability and documentation usefulness.

```swift
mutating func ensureUniqueStorage(
    minimumCapacity requestedCapacity: Int,
    allocate: (_ byteCount: Int) -> UnsafePointer<Void>
) -> (reallocated: Bool, capacityChanged: Bool)
```

## Be Careful With Unconstrained Polymorphism
- `Any`, `AnyObject`, and unconstrained generics can make overload sets ambiguous.
- Semantic overload families still need explicit naming when weak typing collapses distinctions.

Ambiguous pattern:
```swift
values.append([2, 3, 4]) // element append or sequence append?
```

Preferred disambiguation:
```swift
append(_ newElement: Element)
append(contentsOf newElements: S)
```

## Practical Rule
- If overload meaning is not obvious at the call site for weakly typed values, rename APIs to make intent explicit.
references/strive-for-fluent-usage.md
# Strive For Fluent Usage

## Build Grammatical Call Sites
- Prefer names that form readable phrases at use sites.
- Fluency matters most for the base name and first arguments.

```swift
x.insert(y, at: z)
x.subviews(havingColor: color)
```

## Factory And Initializer Naming
- Start factory methods with `make`.
- Do not force the first argument into a phrase with the base name.

```swift
factory.makeWidget(gears: 42, spindles: 14)
let link = Link(to: destination)
```

## Name By Side Effects
- No side effects: noun/query style (`distance(to:)`, `isEmpty`).
- With side effects: imperative verb style (`sort()`, `append(_)`, `print(_)`).

## Mutating/Nonmutating Pairs
- If naturally a verb:
  - Mutating: imperative (`sort`, `append`)
  - Nonmutating: participle (`sorted`, `appending`/`stripping...`)
- If naturally a noun:
  - Nonmutating noun (`union`)
  - Mutating `form` prefix (`formUnion`)

## Protocol And Type Naming
- Protocols describing what something is should be nouns (`Collection`).
- Capability protocols should end in `able`, `ible`, or `ing` (`Equatable`, `ProgressReporting`).
- Types, properties, constants, and variables should read as nouns.
references/use-terminology-well.md
# Use Terminology Well

## Prefer Clarity Over Obscurity
- Avoid obscure terminology when common words preserve meaning.
- Use terms of art only when they provide necessary precision.

## Preserve Established Meanings
- If you use a term of art, keep its accepted meaning.
- Do not redefine terms in ways that surprise experts or mislead newcomers.

## Avoid Unnecessary Abbreviations
- Non-standard abbreviations become hidden terms of art.
- Use abbreviations only when widely established in domain practice.

## Embrace Precedent
- Follow established technical vocabulary in Swift and the broader domain.
- Choose culturally standard names when they improve interoperability of understanding.

Examples:
- Prefer `Array` over inventing a new simplified synonym.
- In math-heavy APIs, `sin(x)` is better than over-explaining the name.
    swift-api-design-guidelines-skill | Prompt Minder