Swift

Swift

Made by DeepSource

Prefer using .last(where:) over .filter { }.last in collections SW-P1009

Performance
Minor
Autofix

Using .filter {}.last to get the last element of a collection is less efficient than using .last(where:). The former method first iterates through the entire collection to filter the elements and then returns the last element. This is less efficient because it allocates an intermediate buffer/allocation. Instead, you can use .last(where:) to directly find the last element that satisfies the given condition without iterating through the entire collection.

Bad Practice

let arr = [1, 2, 3, 4, 5]
let lastEven1 = arr.filter { $0 % 2 == 0 }.last // returns 4

Recommended

let lastEven = arr.last(where: { $0 % 2 == 0 }) // returns 4