Yalamber
Yalamber

Reputation: 7580

Swift various ways of creating empty array what are differences between them?

I looked through docs some forums and found I can create an array in various ways. I am confused which one should we be using?

var testArray = [Int]()
testArray.append(1)

var anotherTestArray: [Int] = []
anotherTestArray.append(1)

var yetAnotherTestArray: Array<Int> = []
yetAnotherTestArray.append(1)

var yetYetYetAnotherTestArray = Array<Int>()
yetYetYetAnotherTestArray.append(1)

This is not empty array but It keeps it's type for each element to be strictly to an Int

var yetYetAnotherTestArray = [1]

Upvotes: 0

Views: 61

Answers (1)

OscarVGG
OscarVGG

Reputation: 2670

I think the cleanest way to create an array is var testArray: [Int] = []

In swift array objects must be the same type. If you want to store different objects of different types use [AnyObject]. However, you should always know what is coming out of it. Since the returning type value will be AnyObject, you have to cast down the value to the type you want.

I really don't recommend using AnyObject as the type of your arrays unless you really know what you are doing.

Here is an example anyway:

let a: [AnyObject] = [1, "a"]
let b = a[0] // An Int
let c = a[1] // A String

Upvotes: 1

Related Questions