为什么在创建嵌套结构的数组时不能使用简短的数组构造函数语法? [英] Why can't I use the short Array constructor syntax when creating an Array of a nested Struct?
问题描述
考虑嵌套在另一个结构中的结构:
struct Struct1 {结构结构 2 {变量名称:字符串?}}
我想创建一个 Struct2
值的数组.起初我尝试过:
var struct2Array = [Struct1.Struct2]()
但这会导致编译器错误:
<块引用>error: invalid use of '()' to call a value of non-function type '[Struct1.Struct2.Type]'var struct2Array = [Struct1.Struct2]()
我可以通过声明变量的类型并使用空数组或使用更详细的语法来创建数组:
var struct2Array: [Struct1.Struct2] = []var struct2ArrayVerbose = Array()
但是为什么我不能对嵌套结构使用速记初始化程序?
这只是语言中的一个漏洞.毕竟,[Type]
语法只是语法糖;正如您所说,如果您使用带有 Array
的真实语法,或者使用 [Type]
但不是作为构造函数,则没有问题.您也可以使用类型别名来解决它:
struct Struct1 {结构结构 2 {变量名称:字符串?}}typealias Struct2 = Struct1.Struct2var struct2Array = [Struct2]()
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?
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]()
这篇关于为什么在创建嵌套结构的数组时不能使用简短的数组构造函数语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!