Reputation: 6452
Is there any difference between the following?
var array1_OfStrings = [String]()
var array2_OfStrings: [String] = []
var array3_OfStrings: [String]
Testing in Playground shows that 1 and 2 are the same but 3 behaves differently.
Can someone explain me the difference please? And also what will be the preferred way to declare an empty array of String
?
Upvotes: 5
Views: 286
Reputation: 7948
While I might be late to the party, there is one thing that needs to be said.
First option set array1_OfStrings
to array of Strings
The other option tells that array1_OfStrings
is array of Strings and then set it empty.
While this might be a really small difference, you will notice it while compiling. For the first option compiler will automatically try to find out what is the type of array1_OfStrings
. Second option won't do that, you will let compiler know that this actually is array of Strings and done deal.
Why is this important? Take a look at the following link: https://thatthinginswift.com/debug-long-compile-times-swift/
As you can see, if you don't declare type of your variable that might impact build performance A LOT.
Upvotes: 4
Reputation: 1514
First two have the same effect.
declare a variable array1_OfStrings
, let it choose the type itself. When it sees [String]()
, it smartly knows that's type array of string.
You set the variable array2_OfStrings
as type array of string, then you say it's empty by []
This is different because you just tell you want array3_OfStrings
to be type array of string, but not given it an initial value.
I think the first one is recommended as The Swift Programming Language uses it more often.
Upvotes: 4