Swift

Swift

Made by DeepSource

Prefer using Array(seq) over seq.map { $0 } to convert a sequence into an Array SW-R1000

Anti-pattern
Major
Autofix

Using the Array initializer Array(seq) is a more concise and performant way of converting a sequence into an Array in Swift, as opposed to using seq.map { $0 }. Here's why:

Performance: When using seq.map { $0 } to convert a sequence into an Array, the map function creates a new array and copies all the elements from the sequence into the new array. The Array initializer, on the other hand, creates an array with the exact same elements as the sequence, without any intermediate steps. This makes Array(seq) more performant than seq.map { $0 } for large sequences.

Readability and Conciseness: Using the Array initializer is more concise and easier to read than using seq.map { $0 }. The Array initializer clearly communicates that you are converting a sequence into an array, whereas seq.map { $0 } requires the reader to understand that you are making a copy of all the elements in the sequence.

In summary, using Array(seq) is a more concise and performant way of converting a sequence into an Array in Swift. Here's an example:

Bad Practice

let seq = [1, 2, 3]
let arr = seq.map { $0 }

Recommended

let seq = [1, 2, 3]
let arr = Array(seq)