Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

swift - 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] = []
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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] = []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...