斯威夫特使方法参数可变吗? [英] Swift make method parameter mutable?

查看:372
本文介绍了斯威夫特使方法参数可变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不创建其他变量的情况下处理此错误?

How can I deal with this error without creating additional variable?

func reduceToZero(x:Int) -> Int {
    while (x != 0) {
        x = x-1            // ERROR: cannot assign to 'let' value 'x'
    }
    return x
}

我不想创建其他变量只是为了存储x的值.甚至有可能做我想做的事吗?

I don't want to create additional variable just to store the value of x. Is it even possible to do what I want?

推荐答案

如其他答案所述,从Swift 3开始,将var放在不推荐使用的变量之前.尽管没有在其他答案中说明,但是可以声明inout参数.想一想:传入一个指针.

As stated in other answers, as of Swift 3 placing var before a variable has been deprecated. Though not stated in other answers is the ability to declare an inout parameter. Think: passing in a pointer.

func reduceToZero(_ x: inout Int) {
    while (x != 0) {
        x = x-1     
    }
}

var a = 3
reduceToZero(&a)
print(a) // will print '0'

这在递归中特别有用.

Apple的inout声明准则可以在

Apple's inout declaration guidelines can be found here.

这篇关于斯威夫特使方法参数可变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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