Richard Clegg
Richard Clegg

Reputation: 3

How to pass new data in to UILabel instead of adding data to the already created string?

Every time I hit generate the password gets bigger, how do I just change the string every time the button is pressed?

import UIKit

class ViewController: UIViewController {
    
    let lettersAndNumbers = ["a", "b", "c", "d", "e", "1", "2", "3"]
    
    var password: String = ""
    
    @IBOutlet weak var passwordText: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func generateButton(_ sender: UIButton) {
        for _ in 1...6 {
            password += lettersAndNumbers.randomElement()!
            passwordText.text = password
        }
    }
}

Upvotes: 0

Views: 91

Answers (3)

Hailey
Hailey

Reputation: 362

You can use didSet to change the text of the label whenever the password changes. didSet is called immediately after the new value is saved.

var password: String = "" {
  didSet {
    passwordText.text = password
  }
} 
@IBAction func generateButton(_ sender: UIButton) {
        for _ in 1...6 {
            password += lettersAndNumbers.randomElement()!
        }
    }

Upvotes: 0

Zulqarnain Naveed
Zulqarnain Naveed

Reputation: 108

Replace your generateButton code to this one.

@IBAction func generateButton(_ sender: UIButton) {
        for _ in 1...6 {
            password += lettersAndNumbers.randomElement()!
        }
            passwordText.text = password
    }

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54706

You are simply appending 6 new characters every time generateButton is called.

You need to reset password instead before appending the characters.

@IBAction func generateButton(_ sender: UIButton) {
    password = ""
    for _ in 1...6 {
        password += lettersAndNumbers.randomElement()!
    }
    passwordText.text = password
}

Unrelated to your question, but you don't need to update the text field in each iteration of the loop, you only need to do it once after password was updated.

You can also get rid of the loop completely by using compactMap and then joined to update password in a single line, so you don't need to reset it, you can just assign the new value directly.

@IBAction func generateButton(_ sender: UIButton) {
    password = (1...6).compactMap { _ in lettersAndNumbers.randomElement() }.joined()
    passwordText.text = password
}

Upvotes: 1

Related Questions