Simple StopWatch app in Swift

In this tutorial, we will see the steps for creating simple StopWatch app in Swift Programming language as shown in the below screenshot.

SimpleStopWatch demo

Click File menu -> New -> select Project from menu list.

Single View Application Xcode

Choose the template as Single View Application and click Next button.

Xcode select language as Swift

Enter name of the Product, Language as Swift then click Next to specify a folder and save the project.

Project Navigator in Xcode

Navigate to Project Navigator and select Main.storyboard. Using the Attributes Inspector, change the background colour for the ViewController to Dark Gray Colour

Attributes Inspector for View Controller

Navigate to Object Library, drag and drop UILabel to View Controller. Then align the label horizontally centred to the View Controller. Using the Attributes Inspector enter the label text as 00:00:00, change the colour to White, make the text centre aligned and increase the the font size to 27.0

Attributes Inspector for UILabel

Now drag and drop two buttons for starting and stopping the timer. Change the button text to Start and Stop respectively and set the Text Color to white.


Now select ViewController.swift in the Project Navigator and delete the file, select Move to Trash in the Confirmation box.


Let us add a new UIViewController file, right click on the SimpleStopWatch folder and select New File from the menu list.


Select the template for the new file as Cocoa Touch Class (under iOS), then click Next


Enter the name of the class as SWViewController, Subclass as UIViewController and Language as Swift. Then click Next and choose the Project folder to save the file.


Navigate to SWViewController.swift and add a IBOutlet for UILabel.

@IBOutlet var displayTimeLabel: UILabel!

Then add two IBActions method for the two buttons, Start and Stop.

@IBAction func start(sender: AnyObject) {

@IBAction func stop(sender: AnyObject) {


Navigate to Main.storyboard, select View Controller and specify the class name as SWViewController using the Identify Inspector

Identity Inspector for Class name

Now you should be able to see the IBActions and IBOutlet defined in the class file using Connection Inspector

Connections Inspector in Xcode 6

Drag and connect the UILabel with the IBOutlets, similarly connect IBActions with the buttons and specify the event as Touch Up Inside.


Select the ViewController under View Controller Scene, click the Resolve Auto Layout Issues option and select Reset to Suggested Constraints. This would ensure that the alignment of controls remains the same for different screen size.


Now if you try to run this project on Simulator, the screen would be as shown below. Nothing should happen on clicking the two buttons as we are yet to add the functionality.


Write Code logic for StopWatch

Navigate to SWviewController.swift file and new function name as updateTime. This function will be used for calculating the time in minutes, seconds and fraction of milliseconds.

Add a new class level variable to the class for storing the start time.

var startTime = NSTimeInterval()

Then add the following code in updateTime method. This is used for calculating the StopWatch time and assigning the value to the UILabel.

func updateTime() {

var currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.

var elapsedTime: NSTimeInterval = currentTime - startTime

//calculate the minutes in elapsed time.

let minutes = UInt8(elapsedTime / 60.0)

elapsedTime -= (NSTimeInterval(minutes) * 60)

//calculate the seconds in elapsed time.

let seconds = UInt8(elapsedTime)

elapsedTime -= NSTimeInterval(seconds)

//find out the fraction of milliseconds to be displayed.

let fraction = UInt8(elapsedTime * 100)

//add the leading zero for minutes, seconds and millseconds and store them as string constants

let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)

//concatenate minuets, seconds and milliseconds as assign it to the UILabel

displayTimeLabel.text = “\(strMinutes):\(strSeconds):\(strFraction)”


Add a new class level NSTimer variable as shown below.

var timer = NSTimer()

Navigate to Start IBAction function and add the following the code.


@IBAction func start(sender: AnyObject) {
	let aSelector : Selector = “updateTime”
	timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
	startTime = NSDate.timeIntervalSinceReferenceDate()

This would start a timer and it repeats at regular time interval of 0.01. Here we specify the “updateTime” function which gets called regularly after the specified interval. We also initialise the startTime variable to the current time. Now when the user taps on Stop button, timer is invalidated and set to nil.

@IBAction func stop(sender: AnyObject) {
	timer == nil

If you try to run this app on the simulator, you should notice the start and stop functionality works and time is getting displayed in the Label. But the user can repeatedly tap the Start button. So when the clock is running if the user taps the Start button, clock restarts again. We can prevent this by adding the following check to start the timer only when the timer is not running.

@IBAction func start(sender: AnyObject) {
	if !timer.valid {
		let aSelector : Selector = “updateTime”
		timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, 	userInfo: nil, repeats: true)
		startTime = NSDate.timeIntervalSinceReferenceDate()

Download the source code from here

In Category: Develop, Programming, Xcode

Ravi Shankar

A polyglot software developer and now exploring Swift and iOS development. If you would like to learn from me then check out services page.

Show 52 Comments
  • Trisha August 1, 2014, 6:46 pm

    Hey, awesome tutorial. I’m using Xcode 6 Beta 4 and for some reason in the function start, the line
    let aSelector : Selector = “updateTime”
    I’m getting the error “invalid character in source file” any idea why this could be?

    • rshankar August 2, 2014, 2:45 am

      Thank you. Look likes the doubling quotes the causing this issue. Can you just retype “updateTime” and see if that resolves the issue

  • Steven Rosenberg August 4, 2014, 4:48 am

    Really great tutorial. I was modifying the app to provide a countdown timer. Every thing crashes when the timer reaches zero. I get an error in the statement:

    displayTimeLabel.text =…. [Exc_Bad_Instruction…]

    How might one avoid this?

    • lio September 18, 2014, 10:26 am

      Hello Steven (and the other!), can you explain the changes of the code you did for making a countdown timer please ?


      • lio September 18, 2014, 12:22 pm

        it was simple !
        var elapsedTime: NSTimeInterval = 5-(currentTime-startTime)

        • rshankar September 18, 2014, 12:24 pm

          Thanks for sharing.

          • Christian November 21, 2015, 11:07 am

            I have a problem when using the countdown, I can not make it stop at “0”. I tried many things but doesn’t work.
            Can you help me?

          • Ravi Shankar November 21, 2015, 11:17 am

            Can you share your project? Probably I can take a look.

  • Steven Rosenberg August 4, 2014, 5:58 am

    Ah, figured it out. Had to add time.invalidate() when the timer reached zero.

    • rshankar August 4, 2014, 1:20 pm

      Thanks for sharing the info.

    • Mike December 8, 2014, 9:08 pm

      Where did you add the timer.invalidate() when the timer reached zero? I am not seeing how to do the test for 0 without it crashing.
      Thank You in advance!

  • Paul August 15, 2014, 11:25 pm

    Great tutorial! Really good resource for people just starting with Swift. I was wondering, would it be possible for you to explain why you used UInt8 constant type instead of different ones? I’m trying to understand the whole conversion into and string constants. Regards

  • Kiran August 17, 2014, 3:12 pm

    assertion failed: file /BinaryCache/compiler_KLONDIKE/compiler_KLONDIKE-600.–x86_64/stdlib/core/FloatingPoint.swift, line 1084

    Implemented all that code in my own program. Kept code basically as-is.

    • rshankar August 17, 2014, 3:57 pm

      can you post the code in line 1084.

  • Kiran August 17, 2014, 3:51 pm

    Also I should note that it seems like me and steven are getting the same error in different places.

  • xxmajia August 28, 2014, 7:59 am

    Hi, i have an compile error at this line:
    timer == nil (can not invoke ‘==’ with an argument list of type blah blah blah)
    i thought it was a mistake by i check your source code, its actually using ==

    Can you explain it a little bit? thanks

    • rshankar August 28, 2014, 8:21 am

      Recent iOS 8 beta changes is showing this error. I think you can get rid of that line (timer == nil ). Can you please give it a try.

  • Arvind September 7, 2014, 5:23 am

    Awesome. It worked perfectly on Xcode 6!! Keep those coming.

  • Jesper Sehested September 20, 2014, 4:08 pm

    Great tutorial! Anybody know how to do, if you want the same button to be use as start and stop button?

    • Halah September 21, 2014, 1:45 pm

      Use a boolean flag and toggle it every time the button is clicked, first true state = start timer, false state = stop timer

      • rshankar September 21, 2014, 1:47 pm

        Thank you!!

        • lio October 14, 2014, 10:27 pm

          Got an example if this code ?

    • rshankar September 21, 2014, 1:50 pm

      As mentioned by Halah, you can use flag to have the same button or use tag property of the button to control the behaviour

  • Aborra September 29, 2014, 6:07 pm

    Hi do you know the code for a white background on swift in spritekit

    • rshankar September 30, 2014, 4:55 am

      Sorry I haven’t worked on spritekit

  • Kobayashi October 2, 2014, 9:34 am

    I followed as your instruction but i had some error below :
    1. Class “SWViewController” has no initializers
    2. ‘required’ initializer ‘init(coder:)’ must be provide by subclass of ‘UIViewController’
    Im using Xcode Version 6.0.1 (6A317)

    Thanks so much

    • rshankar October 3, 2014, 4:40 pm

      Setting the IBOutlet with ! should fix the problem. Could you please try this. @IBOutlet var displayTimeLabel: UILabel!

  • Kobayashi October 5, 2014, 3:10 am

    thanks rshankar.
    But this error involve to NSTimer var , when i delete this var, error was disappeared.
    Can you got this problem before?

    • rshankar October 5, 2014, 3:12 am

      I haven’t come across this problem before.


  • hja October 11, 2014, 4:51 am

    /how i add the ‘clear’ function for this?
    can you show your code..?

  • MarcoAlmeida October 31, 2014, 4:31 am

    Great tutorial!!! I tried to add Hours to your example and it worked, but when the label displays the first hour the minutes does not goes to zero, it keeps counting to 6-, 61, 62 and so on.

    So, do you have any idea of how I could implement a complete timer with hours:minutes:seconds:milliseconds?

    Thanks and Best Regards!!!

  • Atharva November 2, 2014, 6:14 pm

    Hey, I’m building a stopwatch that displays hours, minutes and seconds. The problem is when the minutes reach 60 they don’t reset to 0 they keep on going to 61,62… How can I fix that?

    Can you explain this line of code:

    let strMinutes = minutes > 9 ? String(minutes):“0” + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):“0” + String(seconds)
    let strFraction = fraction > 9 ? String(fraction):“0” + String(fraction)


  • sunny November 19, 2014, 3:15 am

    Hi Sahankar,
    thanks for the tutorial, everything works finr for me except the one thing.
    while time is running, if i pause the time, when i press the play button to resume the pause, its starts from

  • Marko January 30, 2015, 10:01 am

    After stoping the timer, when i press play, it restarts from 0. How could i make the timer resume after stoping it?

  • fustav February 5, 2015, 12:30 pm

    Hello, I need to implement a Timer that log out the user – for security reason – after 3minutes of inactivity.

    How can I handle it with timer and selectors?
    maybe touchesBegan(…)

    Thank you

  • Frank February 15, 2015, 12:01 am

    Hi Sahankar,
    just a question. I’ve use your example into my project, but when i start iphone 5/5s simulator it work great, but if i start iphone 4S/iPad Retina…it fail with this error:

    fatal error: floating point value can not be converted to UInt8 because it is greater than UInt8.max

    Where is my errors?

  • David Elvekjær March 24, 2015, 1:08 pm


    Thanks for a great tutorial, I added a bit functionality, so it can pause and reset timer. Just need to add the connection to the startButton outlet

    • Krishna Thakur February 2, 2016, 2:12 pm

      Hello sir in your modified code
      you have used same button for start and pause and continue. But in my case i have three separate button when i click on continue it is not continuing timer. i have used these line in resume button.

      startButton.setTitle(“Continue”, forState: UIControlState.Normal)
      elapsedTime += startTimeDate.timeIntervalSinceNow

      can you help me please.

  • Brandon April 23, 2015, 6:40 pm

    Great tutorial! How do you get the elapsed time for hours, if we wanted to add hours to our stop watch?

    Thank you!

  • Jordan April 29, 2015, 12:59 pm

    why do we need to delete the ViewController.Swift?? Can anyone explain? Thanks in advance!

    • rshankar April 29, 2015, 1:08 pm

      Thanks for bringing up this question. It was done to have viewcontroller with a different name instead of using the default view controller. You can very well use ViewController.swift or change the viewcontroller and the corresponding class name instead of deleting the file.

      Hope this clarifies your doubt.

  • preethi May 29, 2015, 3:30 pm

    Can I get the tutorial for hh:mm:ss
    in swift ?

  • Gabor June 9, 2015, 2:55 pm

    it is painful to see such solution in a tutorial:

    let strMinutes = minutes > 9 ? String(minutes):“0” + String(minutes)

    while we have:

    let strMinutes = String(format: “%02d”, minutes)

    • rshankar June 9, 2015, 3:18 pm

      Thanks for the feedback. Updated the tutorial with more clean code now.

  • Charlotte June 16, 2015, 7:28 am

    I’d like to produce an audible sound when the timer reaches the end. Can you suggest code for this?

    Great tutorial. Many thanks

  • Charlotte June 18, 2015, 12:29 pm


  • AJ July 24, 2015, 6:00 pm

    Hi, is there a way to do the exact same thing however have the current time viewed and it is ticking as a digital clock? I would appreciate an answer thank you!!

  • boris August 21, 2015, 5:07 pm

    // SWViewController.swift
    // StopWatch
    // Created by Mac Owner on 8/21/15.
    // Copyright (c) 2015 Mac Owner. All rights reserved.

    import UIKit

    class SWViewController: UIViewController {

    override func viewDidLoad() {

    // Do any additional setup after loading the view.

    override func didReceiveMemoryWarning() {
    // Dispose of any resources that can be recreated.

    // MARK: – Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.


    @IBOutlet var displayTimeLabel: UILabel!
    @IBAction func start(sender: AnyObject) {

    @IBAction func stop(sender: AnyObject) {
    can someone please correct my code i am using Xcode 6.4

  • Michael August 29, 2015, 7:05 am

    Great tutorial! I was just wondering if you (or someone else!) could explain the line “elapsedTime -= NSTimeInterval(seconds)” and the similar lines. I’m having a hard time understanding what’s happening here.

  • Eugene Tartakovsky November 7, 2015, 7:05 pm

    Hello Ravi!

    Thanks for the great tutorial. I was solving the same problem together and your guide helped me a lot.

    Also i’ve found interesting answer on stackoverflow:

    Combining your guide and this answer i’ve written a reusable and optimized Stopwatch class for my application.

    I decided i should share it with you and your audience because it is assembled from public sources and with your contribution to it. Here it is:

    Hope it’ll help. Thanks again 🙂

  • Kegham Karsian December 7, 2016, 5:58 pm

    Thanks Ravi. A great professional tutorial. I wanted to know if it is possible to use a custom startTime TimeInterval like 07:46:10 to create a count down timer from this start time instead of a stop watch that increments.

Leave a Comment