Skip to content

Add rule: prefer_single_param_onChange #58

@kj6dev

Description

@kj6dev

Summary

Detect .onChange(of:) modifiers using the two-parameter closure when only the new value is used.

Problem

// Bad - oldValue is unused
.onChange(of: someValue) { oldValue, newValue in
    handleChange(newValue)
}

// Also bad - underscore shows intent but still uses wrong API
.onChange(of: someValue) { _, newValue in
    handleChange(newValue)
}

Preferred

// Good - single parameter closure
.onChange(of: someValue) { newValue in
    handleChange(newValue)
}

// Good - direct method reference
.onChange(of: someValue, perform: handleChange)

Detection Logic

  1. Find .onChange(of:_:) calls (the two-param version)
  2. Check if first closure parameter is:
    • Unused (no references in body)
    • Named _ (explicit discard)
  3. If either, trigger warning

Origin

Discovered via vector DB analysis of AGENT directives in edit logs:

  • "must not use the two parameter onchange when you're only using the new data"
  • "I meant .onChange(of: ..., perform: ...)"

Implementation Notes

  • SwiftSyntax rule in CustomRules package
  • Could offer auto-fix to single-param version
  • Related to closure indirection pattern (separate rule candidate)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions