简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM