Array Init
Prefer using Array(seq)
over seq.map { $0 }
to convert a sequence into an Array
- Identifier:
array_init
- Enabled by default: No
- Supports autocorrection: No
- Kind: lint
- Analyzer rule: No
- Minimum Swift compiler version: 5.0.0
- Default configuration:
Key Value severity warning
Rationale
When converting the elements of a sequence directly into an Array
, for clarity, prefer using the Array
constructor over calling map
. For example
Array(foo)
rather than
foo.↓map({ $0 })
If some processing of the elements is required, then using map
is fine. For example
foo.map { !$0 }
Constructs like
enum MyError: Error {}
let myResult: Result<String, MyError> = .success("")
let result: Result<Any, MyError> = myResult.map { $0 }
may be picked up as false positives by the array_init
rule. If your codebase contains constructs like this, consider using the typesafe_array_init
analyzer rule instead.
Non Triggering Examples
Array(foo)
foo.map { $0.0 }
foo.map { $1 }
foo.map { $0() }
foo.map { ((), $0) }
foo.map { $0! }
foo.map { $0! /* force unwrap */ }
foo.something { RouteMapper.map($0) }
foo.map { !$0 }
foo.map { /* a comment */ !$0 }
Triggering Examples
foo.↓map({ $0 })
foo.↓map { $0 }
foo.↓map { return $0 }
foo.↓map { elem in
elem
}
foo.↓map { elem in
return elem
}
foo.↓map { (elem: String) in
elem
}
foo.↓map { elem -> String in
elem
}
foo.↓map { $0 /* a comment */ }
foo.↓map { /* a comment */ $0 }