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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With