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) }}
那么在VIEwController中我有这个:
var timer = Timer(duration: 5,handler: displayTimeRemaining)func displayTimeRemaining(counter: Int) -> VoID { println(counter)}
这不行,我得到以下内容:
‘Int’不是’SecondVIEwController’的子类型
编辑1:添加完整的代码.
Timer.swift
import UIKitclass 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() }}
SecondVIEwController.swift
import UIKitclass 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) }}
我刚从Swift开始,所以我很绿.你应该如何传回回调?我看过例子,这应该是我想的.我的类的定义是不正确的,因为我传递回调的方式吗?
谢谢
好的,现在有了完整的代码,我能够复制你的问题.我不是100%肯定是什么原因,但我相信它与在类被实例化之前引用一个类方法(displayTimeRemaining)有关.这里有几种方法:选项1:在SecondVIEwController类之外声明处理程序方法:
func displayTimeRemaining(counter: Int) -> VoID { println(counter)}class SecondVIEwController: UIVIEwController { // ... var timer = Timer(duration: 5,handler: displayTimeRemaining)
选项2:通过将class关键字添加到函数声明中,将displayTimeRemaining转换为类型方法.
class SecondVIEwController: UIVIEwController { var timer: Timer = Timer(duration: 5,handler: SecondVIEwController.displayTimeRemaining) class func displayTimeRemaining(counter: Int) -> VoID { println(counter) }
选项3:我相信这将是最符合Swift的思维方式 – 使用闭包:
class SecondVIEwController: UIVIEwController {var timer: Timer = Timer(duration: 5) { println() //using Swift's anonymous method params }总结
以上是内存溢出为你收集整理的如何在Swift中传递回调函数全部内容,希望文章能够帮你解决如何在Swift中传递回调函数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)