我有一个简单的类,init方法接受一个Int和一个回调函数.
class Timer { var timer = NSTimer() var handler: (Int) -> Void init(duration: Int,handler: (Int) -> Void) { self.duration = duration self.handler = handler self.start() } @objc func someMethod() { self.handler(10) } }@H_502_3@那么在ViewController中我有这个:
var timer = Timer(duration: 5,handler: displayTimeRemaining) func displayTimeRemaining(counter: Int) -> Void { println(counter) }@H_502_3@这不行,我得到以下内容: @H_502_3@‘Int’不是’SecondViewController’的子类型 @H_502_3@编辑1:添加完整的代码. @H_502_3@Timer.swift
import UIKit class Timer { lazy var timer = NSTimer() var handler: (Int) -> Void let duration: Int var elapsedTime: Int = 0 init(duration: Int,handler: (Int) -> Void) { self.duration = duration self.handler = handler self.start() } func start() { self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self,selector: Selector("tick"),userInfo: nil,repeats: true) } func stop() { timer.invalidate() } func tick() { self.elapsedTime++ self.handler(10) if self.elapsedTime == self.duration { self.stop() } } deinit { self.timer.invalidate() } }@H_502_3@SecondViewController.swift
import UIKit class SecondViewController: UIViewController { @IBOutlet var cycleCounter: UILabel! var number = 0 var timer = Timer(duration: 5,handler: displayTimeRemaining) 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. } @IBAction func btnIncrementCycle_Click(sender: UIButton){ cycleCounter.text = String(++number) println(number) } func displayTimeRemaining(counter: Int) -> Void { println(counter) } }@H_502_3@我刚从Swift开始,所以我很绿.你应该如何传回回调?我看过例子,这应该是我想的.我的类的定义是不正确的,因为我传递回调的方式吗? @H_502_3@谢谢
好的,现在有了完整的代码,我能够复制你的问题.我不是100%肯定是什么原因,但我相信它与在类被实例化之前引用一个类方法(displayTimeRemaining)有关.这里有几种方法:
@H_502_3@选项1:在SecondViewController类之外声明处理程序方法:
原文链接:https://www.f2er.com/swift/319794.htmlfunc displayTimeRemaining(counter: Int) -> Void { println(counter) } class SecondViewController: UIViewController { // ... var timer = Timer(duration: 5,handler: displayTimeRemaining)@H_502_3@选项2:通过将class关键字添加到函数声明中,将displayTimeRemaining转换为类型方法.
class SecondViewController: UIViewController { var timer: Timer = Timer(duration: 5,handler: SecondViewController.displayTimeRemaining) class func displayTimeRemaining(counter: Int) -> Void { println(counter) }@H_502_3@选项3:我相信这将是最符合Swift的思维方式 – 使用闭包:
class SecondViewController: UIViewController { var timer: Timer = Timer(duration: 5) { println($0) //using Swift's anonymous method params }