Reputation: 1789
Which is better way to declare Array and Dictionary, I have used both:
Array<String>
[String]
For me [String]
is very fast in terms of coding but in reality how both are different in terms of compiler and performance and which one we should follow?
Upvotes: 7
Views: 2300
Reputation: 2982
I would note one difference is that if you are trying to instantiate an array of objects where you need to specify the module (because of naming collisions) the shorthand form appears to choke.
let array1 = [MyModule.MyClass]() // Compile error: Invalid use of '()' to call a value of non-function type '[MyClass.Type]'
let array2 = Array<MyModule.MyClass>() // Works as expected.
Other situations like optional unwrapping or as parameter typing work using shorthand notation. I only have tried in Swift 2.3
Upvotes: 0
Reputation: 4266
The two are equivalent.
Array Type Shorthand Syntax
The type of a Swift array is written in full as Array, where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element]. Although the two forms are functionally identical, the shorthand form is preferred and is used throughout this guide when referring to the type of an array.
Upvotes: 6
Reputation: 917
From iOS Developer Library on Swift...
The type of a Swift array is written in full as Array< Element >, where Element is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [Element]. Although the two forms are functionally identical, the shorthand form is preferred and is used throughout this guide when referring to the type of an array.
Upvotes: 15