Gab*_*iel 106 syntax immutability mutability swift
如何在不创建其他变量的情况下处理此错误?
func reduceToZero(x:Int) -> Int {
while (x != 0) {
x = x-1 // ERROR: cannot assign to 'let' value 'x'
}
return x
}
Run Code Online (Sandbox Code Playgroud)
我不想创建额外的变量来存储x的值.甚至可以做我想做的事情吗?
ach*_*chi 163
如其他答案中所述,从Swift 3开始,在变量被弃用之前放置var.虽然在其他答案中没有说明是声明inout参数的能力.想一想:传入一个指针.
func reduceToZero(_ x: inout Int) {
while (x != 0) {
x = x-1
}
}
var a = 3
reduceToZero(&a)
print(a) // will print '0'
Run Code Online (Sandbox Code Playgroud)
这在递归中特别有用.
Apple的inout声明指南可以在这里找到.
LML*_*LML 44
对于Swift 1和2(对于Swift 3,请参阅achi使用inout参数的答案):let默认情况下,Swift中的函数的参数var如果需要更改值,则将其更改为ie,
func reduceToZero(var x:Int) -> Int {
while (x != 0) {
x = x-1
}
return x
}
Run Code Online (Sandbox Code Playgroud)
GeR*_*yCh 40
'var'参数已弃用,将在Swift 3中删除.因此,分配给新参数似乎是现在最好的方法:
func reduceToZero(x:Int) -> Int {
var x = x
while (x != 0) {
x = x-1
}
return x
}
Run Code Online (Sandbox Code Playgroud)
jos*_*shd 12
Swift3回答传递可变数组指针.
功能:
func foo(array: inout Array<Int>) {
array.append(1)
}
Run Code Online (Sandbox Code Playgroud)
呼吁功能:
var a = Array<Int>()
foo(array:&a)
Run Code Online (Sandbox Code Playgroud)
在Swift中,您只需var在函数声明中的变量名称前添加关键字:
func reduceToZero(var x:Int) -> Int { // notice the "var" keyword
while (x != 0) {
x = x-1
}
return x
}
Run Code Online (Sandbox Code Playgroud)
请参阅Swift书籍"函数"一章中的"常量和变量参数"小节(iBook的第210页,如今).
在某些情况下我们不需要使用 inout
如果您希望更改/范围仅在函数内部,我们可以使用类似的方法:
func manipulateData(a: Int) -> Int {
var a = a
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50784 次 |
| 最近记录: |