Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot assign to value: 'word' is a 'let' constant [duplicate]

Tags:

swift

I get following error: "cannot assign to value: 'word' is a 'let' constant" I can't figure out why this happens. If someone could help me, I would appreciate it a lot.

Here is the code:

import UIKit

class ViewController: UIViewController {

    var word1 = ""
    @IBOutlet weak var label: UILabel!

    func writeWord(word: String){
        word = "Example"
    }

    @IBAction func button(sender: AnyObject) {
        writeWord(word1)
        label.text = word1
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
like image 782
Fabio Laghi Avatar asked Aug 12 '16 08:08

Fabio Laghi


2 Answers

what do you want to achieve there?

func writeWord(word: String){
    word = "Example"
}

only way to do that is:

func writeWord(word: String){
    var word = word
    word = "Example"
}
like image 106
Lu_ Avatar answered Oct 20 '22 17:10

Lu_


See this answer.

This seems to solve your question but only for versions before Swift 3.

The parameters to functions in Swift are immutable/you can't edit them. (src)

Also, strings are value types—not reference types. That means, quite obviously, that the parameter word is not a reference to the variable passed into the function.

In order to update a value, you would have to add a return to the function or have a class variable, word, accessed by self.word.

If you decide to return a value, you would do so like this:

func writeWord(word: String) -> String {
    var mutableWord = word
    // do stuff to word(?)
    return mutableWord
}

I honestly don't really know why you're trying to do so I'm just guessing here at what your aim is.

Do you want:

func writeWord(word: String) {
    word1 = word
    word2 = word
    word3 = word
    // ...
}
like image 16
Daniel Avatar answered Oct 20 '22 17:10

Daniel