问题
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