swift 中 函数内定义变量应该用 let 还是用 var 的问题

chinanoahli
  • 160

刚开始接触swift,感觉上写起来还是比较方便,但是今天写一个小联系的时候遇到一个小提示,感觉有点无法理解,下面上代码

maxBalance(345.12, 1000.80, 233.10, 104.80, 99.90)
minBalance(345.12, 1000.80, 233.10, 104.80, 99.90)

var account1 = ("state bank personal", 1011.10)
var account2 = ("state bank business", 24309.63)

func deposit (amount : Double, account : (name : String, balance : Double)) -> ( String, Double) {
    let newBalance : Double = account.balance + amount //没有警告
    return (account.name, newBalance)
}

func withdraw (amount: Double, account : (name : String, balance : Double)) -> (String, Double) {
    var newBalance : Double = account.balance - amount //Variable 'newBalance' was never mutated; consider changing to 'let' constant
    return (account.name, newBalance)
}

let mondayTran = deposit
let fridayTran = withdraw

let mondayBalance = mondayTran (300.0, account: account1)
let fridayBalance = fridayTran (1200, account: account2)

以前写的是C,按照以前的思维理解,这种量应该定义为变量而非常量,但为何在swift里面编译器会建议将这个量定义为常量?
还是说我理解错了 letvar 的意思?

回复
阅读 3.1k
3 个回答
✓ 已被采纳

首先,newBalance 在它的生命周期内并未被改变,所以编译器才会提示你这个应该是 let 声明为不可变量。
其次,newBalance 是值类型,遵循的是 copy 而非引用传递。

编译器又没有思维,它看到当前代码中不改变就会建议你用let

但是你是人类,你才真正能判断这个量在逻辑上应不应该改变,自信一点..

宣传栏