JAL JAL - 3 months ago 8
Swift Question

Why can't I use the short Array constructor syntax when creating an Array of a nested Struct?

Consider a struct nested inside another struct:

struct Struct1 {
struct Struct2 {
var name: String?
}
}


I want to create an array of
Struct2
values. At first I tried:

var struct2Array = [Struct1.Struct2]()


But this gives the compiler error:


error: invalid use of '()' to call a value of non-function type '[Struct1.Struct2.Type]'
var struct2Array = [Struct1.Struct2]()



I can create an array by declaring the type of the variable and using an empty array, or with the more verbose syntax:

var struct2Array: [Struct1.Struct2] = []
var struct2ArrayVerbose = Array<Struct1.Struct2>()


But why can't I use the shorthand initializer for a nested Struct?

Answer

It's just a hole in the language. After all, the [Type] syntax is just syntactic sugar; as you rightly say, if you use the real syntax with Array<Type>, or use [Type] but not as a constructor, there's no problem. You can also work around it with type alias:

struct Struct1 {
    struct Struct2 {
        var name: String?
    }
}

typealias Struct2 = Struct1.Struct2

var struct2Array = [Struct2]()