16

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.
    }
}
julia_v
  • 593
  • 3
  • 18
Fabio Laghi
  • 227
  • 1
  • 3
  • 6

3 Answers3

33

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"
}
Lu_
  • 2,577
  • 16
  • 24
16

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
    // ...
}
Daniel
  • 3,188
  • 14
  • 34
  • Actually I have more variables (word1, word2, ...). I want them to be empty strings unless they get passed in the function writeWord. When they go thorugh the function I want another string ("Example") to be assigned to them. Finally I want to use the variable word1 (which should be "Example") to do other stuff. – Fabio Laghi Aug 12 '16 at 09:17
  • Thanks.. it is working in Swift 4 also. – Minhaz Panara Apr 12 '19 at 09:30
  • 1
    You can use the same namespace `var word = word`. – Leo Dabus May 21 '20 at 02:22
-5

In Swift 2 you have to write method

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

instead of

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

because the param passed in function are by default let that is constant and cannot change its value. To change param value you have to explicitly make mutable by making it variable.In Swift 3 you may not face this problem.

Sunil Sharma
  • 2,653
  • 1
  • 25
  • 36