变量 p 在初始化前通过引用传递 [英] Variable p passed by reference before being initialized

查看:138
本文介绍了变量 p 在初始化前通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有函数的 Human 类,该函数可以接收任意数量的人并确定某人是否比其中任何一个人年长,然后返回一个包含他/她比他/她年长的人的数组.

func isOlderThan(people: Human...) ->[人类] {var p: [人类]为人在人{如果年龄 >人.年龄{p.append(人)}}返回 p}

然而在

p.append(person)

我收到错误

变量p在初始化前通过引用传递

有人知道这是为什么吗?谢谢!

解决方案

你对 p 的声明只是一个声明.你还没有初始化它.你需要把它改成

var p = [人类]()

或者,正如@MartinR 指出的那样,

var p: [人类] = []

还有其他等效的构造,但重要的是您必须为声明的变量分配一些东西(在这两种情况下,都是一个接受 Human 成员的空数组).

更新为了完整起见,您还可以使用:

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 error

Variable p passed by reference before being initialized

Anyone sure why this is? Thanks!

解决方案

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>()

这篇关于变量 p 在初始化前通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆