SwiftFormat icon indicating copy to clipboard operation
SwiftFormat copied to clipboard

[New Rule]: A standard style for empty collection inits

Open jshier opened this issue 1 year ago • 5 comments

Barring other considerations, these two forms mean the same thing for Array and Set:

let x: [Int] = []
let x = [Int]()

let y: Set<Int> = []
let y = Set<Int>()

I don't see a rule to allow preferring the first form over the second, is it possible?

jshier avatar Sep 25 '24 18:09 jshier

It could make sense to support this as an option in the propertyType rule. Agreed this would be a good addition.

calda avatar Sep 25 '24 18:09 calda

A similar example related to literals is:

let width: Double = 10
// vs
let width = Double(10)

calda avatar Sep 25 '24 19:09 calda

@calda it was at one point recommended not to use Double(0) because it's not merely an alternative syntax for casting; it actually incurs an additional runtime cost:

https://stackoverflow.com/questions/42705484/why-literals-produce-more-efficient-code-than-initializers

I've no idea if that's still the case now though. In any case the cost is presumably trivial.

nicklockwood avatar Sep 25 '24 19:09 nicklockwood

If you did want to that, it should probably be a separate setting or a configuration option separate from the collection values.

jshier avatar Sep 25 '24 19:09 jshier

I would like to create an implementation of this just for Array and Dictionary. Maybe it should be for collections in general.

My assumption, based on reading the Array source code, is that

let x: [Int] = []

will create 2 arrays because it will need to create the rhs argument (calling Array.init()) and pass that to the initialisation of the lhs variable (calling Array.init(arrayLiteral:)).

This would be true for any type conforming to ExpressibleByArrayLiteral or ExpressibleByDictionaryLiteral, although I'm not sure if SwiftFormat can actually check that as part of the flow, so for now I would just like to do it for Array and Dictionary declarations.

via-guy avatar Aug 21 '25 08:08 via-guy