powing
(Albert)
March 21, 2021, 3:27am
1
What is the difference between initialising an array, or passing in an empty array, for use in a return statement?
func returnArrayData() -> [String] {
var returnArray: [String]()
var returnArray: [String] = []
return returnArray
}
Is it just the same thing ?
Karl
(👑🦆)
March 21, 2021, 4:09am
2
This is not valid Swift. I think you meant to write:
var returnArray = [String]()
var returnArray: [String] = []
In which case, they are equivalent.
Ray_Fix
(Ray Fix)
March 21, 2021, 4:25am
3
Yes, typo noted above aside, they are effectively the same. The style guide that I use prefers the latter.
Interestingly, this came up on twitter a few days ago.
Don't miss @algal 's reply.
powing
(Albert)
March 21, 2021, 11:47am
4
Apologies, I do recognise the code as not being compilable, and should have left a comment, it was just to visually illustrate the syntax I was asking the question on.
So basically the same ?
I found this recent thread on twitter by @Ben_Cohen that explains the differences, and his recommendation of preferring var returnArray: [String] = []
: https://twitter.com/AirspeedSwift/status/1372912670542757891
1 Like
powing
(Albert)
March 21, 2021, 10:32pm
6
Thanks wowbagger that was an interesting brainstorming session from more seasoned developers.
I was going to switch but I think now that I'll keep with explicit declarations.
Thanks to all.