为什么在创建嵌套Struct的Array时不能使用简短的Array构造函数语法? [英] Why can't I use the short Array constructor syntax when creating an Array of a nested Struct?

查看:101
本文介绍了为什么在创建嵌套Struct的Array时不能使用简短的Array构造函数语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个嵌套在另一个结构中的结构:

Consider a struct nested inside another struct:

struct Struct1 {
    struct Struct2 {
        var name: String?
    }
}

我想创建一个Struct2值的数组.一开始我尝试过:

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>()

但是为什么我不能对嵌套的Struct使用简写初始化器呢?

But why can't I use the shorthand initializer for a nested Struct?

推荐答案

这只是语言上的一个漏洞.毕竟,[Type]语法只是语法糖.正确地说,如果您将实语法与Array<Type>一起使用,或者将[Type]用作构造函数,则没有问题.您也可以使用别名别名解决此问题:

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]()

这篇关于为什么在创建嵌套Struct的Array时不能使用简短的Array构造函数语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆