Differentiating between an initialised variable or default data

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 ?

This is not valid Swift. I think you meant to write:

var returnArray = [String]()
var returnArray: [String] = []

In which case, they are equivalent.

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. :slight_smile:

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

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.

Terms of Service

Privacy Policy

Cookie Policy