The current style guide says that arrays and dictionaries be initialized in the following way.
var names = [String]()
var lookup = [String: Int]()
I would like to push back on this in favor of:
var names: [String] = []
var lookup: [String: Int] = [:]
Here is my rationale:
[Type]()
looks foreign, especially for a newcomer. To me, : [Type] = []
simply reads better in many cases. var stuff = [1, 2, 3, 4, 5, // ... 100 more numbers
106.7, 107, "haha", nil, 108, 109]
The type checker needs to scan all of the elements to properly type infer stuff
. Even when there are no tricks ("haha"), I have seen this bog down the editor. (Hello rainbow.) Making the type checker work for you to double check your work seems like a good idea.
var items: [Type] = []
form. https://twitter.com/_jackhl/status/646480946619805697What do you think?
@rayfix I've grown to prefer your suggested format i.e. var names: [String] = []
My rational is that this approach looks more consistent with the approach you would take when you want to define an array with a let
constant. (You would not initialize it to an empty array since you would not be able to change it later)
For example in the case of a class:
class SimpleClass {
let array: [String]
init(array: [String]) {
self.array = array
}
}
Or when defining a constant array whose value depends on a condition.
let array: [String]
if condition {
array = array1
} else {
array = array2
}
Big +1 on this!
I chose the var array: [Type] = []
notation for my courses because it allows me to teach arrays (and dictionaries) fairly early on in my courses. My teaching approach is to start from scratch, add only one topic at a time and never leave things unexplained. This notation allows me to do that because it doesn't involve any topics the students aren't yet familiar with at the point, such as initializers or generics.
Love it. I use your suggested syntax in my own codebases; definition and type of the var on one side of the equation, value on the other. Nice and simple.
Most helpful comment
@rayfix I've grown to prefer your suggested format i.e.
var names: [String] = []
My rational is that this approach looks more consistent with the approach you would take when you want to define an array with a
let
constant. (You would not initialize it to an empty array since you would not be able to change it later)For example in the case of a class:
Or when defining a constant array whose value depends on a condition.