-5

I get that var is for defining variables and let is for defining constants.

My issue is, I am "able" to change my let constants. For example, my test code takes in two inputs from the user, their name and emails. When a button is pressed, it will update two labels.

However, when I change the inputs, it will also change the labels. So why doesn't it crash or anything?

class ViewController: UIViewController {
    @IBOutlet weak var emailInput: UITextField!
    @IBOutlet weak var nameInput: UITextField!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var label2: UILabel!

    @IBAction func actionButton(_ sender: Any) {
        let text = nameInput.text
        let email = emailInput.text

        label.text = text
        label2.text = email
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    Possible duplicate of [What is the difference between \`let\` and \`var\` in swift?](https://stackoverflow.com/questions/24002092/what-is-the-difference-between-let-and-var-in-swift) – alanpaivaa Apr 11 '19 at 02:25
  • 1
    `var` lets you change the value that it points to `let` does not. `IBOutlet` needs to be `var` because the values are assigned AFTER the object is constructed – MadProgrammer Apr 11 '19 at 02:25
  • 4
    Where do you think you are attempting to change a `let` constant? None of your code makes any such attempt. – rmaddy Apr 11 '19 at 02:25
  • 1
    A thing may be a constant yet mutable. See https://stackoverflow.com/questions/27364117/is-swift-pass-by-value-or-pass-by-reference/27366050#27366050 – matt Apr 11 '19 at 02:27

1 Answers1

0

var is a variable, it can be changed once defined

let is a constant, it can't be changed once defined.

IBOutlet needs to be a variable (var) because the values are defined after the object is made.

Here you are not changing you variables:

let text = nameInput.text
let email = emailInput.text

label.text = text
label2.text = email

Because the labels are variables (var), they can be changed. Every time you click your button, the constants (let) is being re-made and for this reason they are not being changed but redefined as a new constant.

  • Correction: they are not really being redefined. Once the scope of the action is done the constants are de-allocated, so next time the button gets tapped they are created afresh. – GoodSp33d Apr 11 '19 at 05:09