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.
}
}
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"
}
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
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With