0

According to the Apple documentation, this is the proper way to create an empty array of a specific object type in Swift 4:

var output_list = [Output]()

In the wild I have seen slightly different array declarations. I believe the following is functionally identical to the previous declaration:

var output_list: [Output] = []

However I'm fairly confident that the following two declaration methods have nuanced differences from the above:

var output_list: [Output]?
var output_list: [Output]!

What are the effective differences to the above listed methods of declaring an array as as instance variable in a Swift 4 class?

EDIT: Okay I understand that for the last two examples the variable declaration is an optional, not a generic array declaration. What about this:

var output_list: [Output?]

Is this effectively the same as var output_list = [Output]()?

Also, is var output_list = [Output]() === var output_list: [Output] = []?

Ben Harold
  • 6,242
  • 6
  • 47
  • 71
  • 1
    Your question is not about Arrays, it's about optionals. The first 2 declarations are NOT optionals, they are just simple variables already initialized. The latter 2 declarations are Optionals, they may or may not have an array, but NONE of the two are actually initialized. The one with the "?" says "this optional variable may or may not have an array". The one with the "!" says, "this optional variable SHOULD have an array, and may be used as a normal variable" the latter will crash if you access it without initializing it. – Pochi Feb 09 '18 at 03:20
  • @Pochi Thanks! The optionals answer clarified quite a bit but I'm still wondering about the difference in syntax between the first two examples. – Ben Harold Feb 09 '18 at 03:41
  • There's no difference in result. The difference is that using " : " states the type of the variable. So the second example initialize an array which will hold 'Output's because that's the type you defined. The first example omits this because it can be directly implied from the result of the assignment. The actual "complete" declaration is "var output_list : [Output] = [Output]()" but it isn't needed since swift can imply many things for you. – Pochi Feb 09 '18 at 04:36

0 Answers0