Search code examples
swiftloopstimer

Swift Timer Loop doesn't trigger but view and controller are connected


I'm trying to print the title "⚡️FlashChat" one letter at a time.
I'm coding along with a video and I've checked my code against the instructor's and it matches.
Right now, the title prints in its entirety when the sim is built.
I've adjusted the withTimeInterval to see fit that was set too quickly.
If I remove the loop and just execute the titleLabel.text = "", the title disappears, so it is connected correctly.

Thanks in advance!

import UIKit

class WelcomeViewController: UIViewController {
    
    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.text = ""
        
        var charIndex = 0.0
        let titleText = "⚡FlashChat"
        for letter in titleText {
            Timer.scheduledTimer(withTimeInterval: 7.0
                * charIndex, repeats: false) {(timer)
                in
                self.titleLabel.text?.append(letter)}
        }
        charIndex += 1
        
    }
    
}

Code


Solution

  • You're incrementing charIndex outside your for loop. So interval will always be equal to 0