3

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?

JAL
  • 41,701
  • 23
  • 172
  • 300
  • Another one here: [Why can't I instantiate an empty array of a nested class?](http://stackoverflow.com/questions/25682113/why-cant-i-instantiate-an-empty-array-of-a-nested-class). – Martin R Aug 19 '16 at 14:44
  • @MartinR ah, guess I should have searched for nested types in general. I though this was just an issue with structs. Thanks. – JAL Aug 19 '16 at 14:45
  • @MartinR Nice one. Now that we have bugs.swift.org, he should still file a bug; it's a lot more responsive. – matt Aug 19 '16 at 14:45
  • Sometimes I have the feeling that I spend more time hunting for duplicates than answering ... :) – In this case a search for `[swift] nested type array` was immediately successful. – Martin R Aug 19 '16 at 14:47
  • Opened a ticket on Swift.org https://bugs.swift.org/browse/SR-2428 – JAL Aug 19 '16 at 14:54
  • @MartinR I know the feeling. Guess I should have searched better – JAL Aug 19 '16 at 14:54

1 Answers1

5

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]()
matt
  • 515,959
  • 87
  • 875
  • 1,141