Swift

Swift

Made by DeepSource

Prefer using min() or max() over sorted().first or sorted().last SW-P1011

Performance
Major
Autofix

Using sorted().first or sorted().last can be inefficient, as the entire collection needs to be sorted, which is not required if we only need the minimum or maximum element. This can cause performance issues, especially when dealing with large collections.

Using min() or max() is more efficient as they only traverse through the collection once and return the required element directly. It also makes the code more readable and concise.

Bad Practice

let arr = [2, 6, 1, 9, 4]
let max = arr.sorted().last
let min = arr.sorted().first

Recommended

let arr = [2, 6, 1, 9, 4]
let max = arr.max()
let min = arr.min()