Matt Gibson
Matt Gibson

Reputation: 38238

Why can't I instantiate an empty array of a nested class?

I seem to be having problems instantiating an empty array of a nested class type using the [foo]() style syntax:

// Playground - noun: a place where people can play

class outsideClass {

}

class Wrapper {
    class InsideClass {
    }
}

var foo = [outsideClass]() // Works fine

// Invalid use of '()' to call a value of non-function type '[Wrapper.InsideClass.Type]'
var bar = [Wrapper.InsideClass]() 

Is this something I'm misunderstanding—it's before my coffee, but I've checked the release notes, and I think you should be able to refer to nested classes like this—or a bug in beta 7?

This works fine as a workaround:

var foobar: [Wrapper.InsideClass] = []

Upvotes: 22

Views: 1586

Answers (2)

kandelvijaya
kandelvijaya

Reputation: 1585

Another way to do is to use Array<T>() constructor.

let arrayOfNestedClass = Array<Wrapper.InsideClass>()

Upvotes: 1

Matt Gibson
Matt Gibson

Reputation: 38238

This definitely looks like a bug in the compiler, especially as you're allowed to instantiate an empty array of a nested class just fine; it simply doesn't work with the initialiser syntax.

I'll raise a bug. In the meantime, for anyone experiencing the problem, you can work around it by using assignment syntax with an empty array and a specified class for the variable, rather than constructor syntax:

 var foobar: [Wrapper.InsideClass] = []

Upvotes: 38

Related Questions