调用自定义计时器 Class

Invoking a custom Timer Class

我拼凑了一个计时器 class 来将 NSTimer 与我所有的 ViewController 一起使用,代码如下

import Foundation

class Timer {
   var timer = NSTimer()
   var handler: (Int) -> ()

   let duration: Int
   var elapsedTime: Int = 0

   init(duration: Int, handler: (Int) -> ()) {
      self.duration = duration
      self.handler = handler
   }

   func start() {
      self.timer = NSTimer.scheduledTimerWithTimeInterval(30,
          target: self,
          selector: Selector("chkProgress"),
          userInfo: nil,
          repeats: true)
   }

   func stop() {
      timer.invalidate()
   }

   @objc func chkProgress() {
      self.elapsedTime++

      self.handler(elapsedTime)

      if self.elapsedTime == self.duration {
          self.stop()
      }
   }

   deinit {
      self.timer.invalidate()
   }
}

然后在每个 ViewController 我可以检查时间进度,然后相应地显示一条消息。问题是当我尝试调用它时

我试过了

var timer = Timer()
var timer = Timer(30)
var timer = Timer(30,30)

结果消息总是一样的,告诉我我不能调用类型为 (int,int) 的 Timer,这就是 init 中 duration() 的设置方式

我做错了什么?

参数不带int,int。他们接受一个整数和一个闭包。

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

您还需要修复您的计时器代码;

class Timer {
    var timer = NSTimer()
    var handler: (x:Int) -> ()

    let duration: Int
    var elapsedTime: Int = 0

    init(duration: Int, handler: (Int) -> ()) {
        self.duration = duration
        self.handler = handler
    }

    func start() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(30,
            target: self,
            selector: Selector("chkProgress"),
            userInfo: nil,
            repeats: true)
    }

    func stop() {
        timer.invalidate()
    }

    @objc func chkProgress() {
        self.elapsedTime++

        self.handler(x: elapsedTime)

        if self.elapsedTime == self.duration {
            self.stop()
        }
    }

    deinit {
        self.timer.invalidate()
    }
}

//定时器的实现

var t = Timer(duration: 30, handler:{ (x:Int) -> Void in
            //Do soemthing with x;
        });