Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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] = []
like image 438
Matt Gibson Avatar asked Sep 05 '14 08:09

Matt Gibson


2 Answers

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] = []
like image 118
Matt Gibson Avatar answered Oct 17 '22 17:10

Matt Gibson


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

let arrayOfNestedClass = Array<Wrapper.InsideClass>()
like image 1
kandelvijaya Avatar answered Oct 17 '22 17:10

kandelvijaya