Variable p passed by reference before being initialized

Brejuro picture Brejuro · Jul 19, 2014 · Viewed 18.2k times · Source

I have a Human class with a function that takes any amount of people and determines if someone is older than any of those people, then returns an array with the people he/she is older than.

func isOlderThan(people: Human...) -> [Human] {
    var p: [Human]

    for person in people {
        if age > person.age {
            p.append(person)
        }
    }
    return p
}

However at

p.append(person)

I'm getting the error

Variable p passed by reference before being initialized

Anyone sure why this is? Thanks!

Answer

Grimxn picture Grimxn · Jul 19, 2014

Your declaration of p is just that, a declaration. You haven't initialised it. You need to change it to

var p = [Human]()

Or, as @MartinR points out,

var p: [Human] = []

There are other equivalent constructs, too, but the important thing is you have to assign something to the declared variable (in both cases here, an empty array that will accept Human members).

Update For completeness, you could also use:

var p: Array<Human> = []

or

var p = Array<Human>()