Prefer Key Path

Use a key path argument instead of a closure with property access

  • Identifier: prefer_key_path
  • Enabled by default: No
  • Supports autocorrection: Yes
  • Kind: idiomatic
  • Analyzer rule: No
  • Minimum Swift compiler version: 5.2.0
  • Default configuration:
    KeyValue
    severity warning
    restrict_to_standard_functions true

Non Triggering Examples

f {}
f { $0 }
f { $0.a }
let f = { $0.a }(b)
//
// restrict_to_standard_functions: false
//

f {}

//
// restrict_to_standard_functions: false
//

f() { g() }

//
// restrict_to_standard_functions: false
//

f { a.b.c }

//
// restrict_to_standard_functions: false
//

f { a, b in a.b }

//
// restrict_to_standard_functions: false
//

f { (a, b) in a.b }

//
// restrict_to_standard_functions: false
//

f { $0.a } g: { $0.b }

//
// restrict_to_standard_functions: false
//

[1, 2, 3].reduce(1) { $0 + $1 }

f.map(1) { $0.a }
f.filter({ $0.a }, x)
#Predicate { $0.a }
let transform: (Int) -> Int = nil ?? { $0.a }

Triggering Examples

f.map { $0.a }
f.filter { $0.a }
f.first { $0.a }
f.contains { $0.a }
f.contains(where: { $0.a })
//
// restrict_to_standard_functions: false
//

f({ $0.a })

//
// restrict_to_standard_functions: false
//

f(a: { $0.b })

//
// restrict_to_standard_functions: false
//

f(a: { a in a.b }, x)

f.map { a in a.b.c }
f.allSatisfy { (a: A) in a.b }
f.first { (a b: A) in b.c }
f.contains { $0.0.a }
f.compactMap { $0.a.b.c.d }
f.flatMap { $0.a.b }
//
// restrict_to_standard_functions: false
//

let f: (Int) -> Int = { $0.bigEndian }

transform = { $0.a }