更新为了完整起见,您还可以使用:var p: Array= [] 或 var p = Array()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 errorVariable p passed by reference before being initializedAnyone sure why this is? Thanks! 解决方案 Your declaration of p is just that, a declaration. You haven't initialised it. You need to change it tovar 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).UpdateFor completeness, you could also use:var p: Array<Human> = []or var p = Array<Human>() 这篇关于变量 p 在初始化前通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 07:23