Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 510
Rainier Wolfcastle Avatar asked Sep 08 '14 06:09

Rainier Wolfcastle


2 Answers

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],
]
like image 77
Vinod Joshi Avatar answered Oct 21 '22 14:10

Vinod Joshi


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

like image 42
Martin R Avatar answered Oct 21 '22 13:10

Martin R