[英]How to declare and initialise an array in Swift
I have a class in Swift that I'm trying to write that has a variable of an array of objects. 我在Swift中有一个类,我正在尝试编写具有对象数组变量的类。 Is there a better way to write this? 有没有更好的方法来写这个?
var myvar: Array<MyClass> = Array<MyClass>()
Without the bit after the = sign, the compiler complains about my AppDelegate having no initializers. 如果没有=符号之后的位,编译器会抱怨我的AppDelegate没有初始化器。 The above way seems a bit lengthy (though it's no more terse than the c# equivalent, I guess). 上面的方法看起来有点冗长(虽然它不比c#等价物简洁,但我猜)。 I'd just like to know if there's a shortcut. 我想知道是否有捷径。 Thanks. 谢谢。
To create an empty array or dictionary, use the initialiser syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
let individualScores = [75, 43, 103, 87, 12]
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
You can initialize the variable with an empty array: 您可以使用空数组初始化变量:
var myvar: Array<MyClass> = []
or use automatic type inference: 或使用自动类型推断:
var myvar = Array<MyClass>()
In addition, you can write Array<MyClass>
as [MyClass]
. 此外,您可以将Array<MyClass>
编写为[MyClass]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.