jeanpier_re
jeanpier_re

Reputation: 835

How to initialize an array before referencing it Swift

Why is it that when I create arr, an array then try to populate it with integers using a for-in loop it, gives me an error when I don't initialize it. From what I can tell it is initialized when I write "var arr," but obviously not so what does writing var arr actually do if not initialize it.

Error Example

var arr : [Int] //Error Message: Variable 'arr' passed by reference before being initialized
for i in 1...10 {
    arr += [i]
}
arr //Error Message: Variable 'arr' used before being initialized

Working Example

var arr : [Int] = [] //Allocating memory?
for i in 1...10 {
    arr += [i]
}
arr

Upvotes: 3

Views: 1606

Answers (1)

GoZoner
GoZoner

Reputation: 70225

Just saying var arr does not initialize your array. Should the initial value be an empty array? Should it have N copies of a given value? If it is declared to hold type A objects, should it be initialized with subtypes of A.

So you provide an initial value; the simplest is [] - an empty array.

Upvotes: 7

Related Questions