Why do I not need an Initializer in Swift for an empty array?

Why do I not need to initialize an empty Array as follows:

var myValues: Array()

When I try that in Xcode, I get an error message regarding the intitializer. Would someone please tell me the reason the initializer is not necessary?

That isn't valid Swift. Can you give a more complete example?

1 Like

You probably need to specify the generic type! :grinning: (Arrays of what?)

For a type T, Array<T> and [T] are equivalent expressions

/// These all express the exact same thing: an empty `Array<Int>`!
var myValues = Array<Int>()  // This is probably what you wanted to do
var myValues = [Int]()
var myValues: Array<Int> = .init()  // we can use this `.init()` without specifying the type, because the type of myValues was explicitly given
var myValues: [Int] = .init()  // same comment as above
var myValues: Array<Int> = []  // same comment as above

As a refresher, valid Swift syntax is: var variableName: Type = value/initializer (in your original post, you put an initializer in the space where the Type is supposed to be; that might be one of the reasons for the strange errors).

1 Like

What the heck, I posted the wrong code. I meant to post the following:

var myValues: Array<Int>()

I was trying to create an empty array of Int type

Thank you, I see where I went wrong. The colon is only intended indicate the type, not to create the Array (which makes sense since it is an assignment operator). Thank you!

2 Likes