SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Empty Array Initialize

Open inotetw opened this issue 2 years ago • 2 comments
trafficstars

New rule request

array initialize using [] instead ()

Bad

var emptyArray = [Int]()

Good

var emptyArray: [Int] = []
  1. using [] is more common and preferred due to its readability and simplicity. It is a more straightforward way to indicate that you are initializing an empty array of a specific type.
  2. using () to initialize an empty array might lead to confusion, as it resembles tuple syntax, which may suggest that you are creating a tuple.

inotetw avatar Aug 04 '23 07:08 inotetw

I think this is a matter of taste. Which style is "good" and which is "bad" is subjective.

For instance, people might like to omit types wherever possible, so they write let b = true, var i = 3, ... and in turn would also prefer let a = [Int]() to be consistent.

That said, this potential new rule should support both styles (by configuration).

SimplyDanny avatar Aug 04 '23 18:08 SimplyDanny

If you compare the machine code of these, "Bad" is actually more efficient (and less typing) 😄

soffes avatar May 10 '24 21:05 soffes