How to declare and initialise an array in Swift

主宰稳场 提交于 2020-01-13 14:01:46

问题


I have a class in Swift that I'm trying to write that has a variable of an array of objects. 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. The above way seems a bit lengthy (though it's no more terse than the c# equivalent, I guess). I'd just like to know if there's a shortcut. Thanks.


回答1:


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].




回答2:


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],
]


来源:https://stackoverflow.com/questions/25718596/how-to-declare-and-initialise-an-array-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!